在实体框架4,code只(CTP3),你怎么在POCO的EntityConfiguration类中的属性设置默认值?
公共类Person
{
公众诠释编号{获得;组; }
公共字符串名称{;组; }
公开日期时间CreatedOn {获得;组; }
}
公共类PersonConfiguration:EntityConfiguration<人>
{
公共PersonConfiguration()
{
物业(P => p.Id).IsIdentity();
属性(p值=> p.Name).HasMaxLength(100);
//为CreatedOn设置默认值?
}
}
解决方案
通过实体框架4.3的版本中,您可以通过迁移做到这一点。
EF 4.3 code首先迁移演练
因此,使用你的榜样,它会是这样的:
公共部分类AddPersonClass:DbMigration
{
公众覆盖无效向上()
{
CREATETABLE(
人,
C =>新
{
n = c.Int(可空:假的,身份:真)
名称= c.String(最大长度:100)
CreatedOn = c.DateTime(可空:假的,设置defaultValue:DateTime.UtcNow)
})
.PrimaryKey(T => t.Id);
}
公共超越控制无效向下()
{
//命令时,迁移放倒了
}
}
In Entity Framework 4, Code Only (CTP3), how do you set a default value for a property in the POCO's EntityConfiguration class?
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
}
public class PersonConfiguration : EntityConfiguration<Person>
{
public PersonConfiguration()
{
Property(p => p.Id).IsIdentity();
Property(p => p.Name).HasMaxLength(100);
//set default value for CreatedOn ?
}
}
解决方案
With the release of Entity Framework 4.3 you can do this through Migrations.
EF 4.3 Code First Migrations Walkthrough
So using your example it would be something like:
public partial class AddPersonClass : DbMigration
{
public override void Up()
{
CreateTable(
"People",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 100),
CreatedOn = c.DateTime(nullable: false, defaultValue: DateTime.UtcNow)
})
.PrimaryKey(t => t.Id);
}
public overide void Down()
{
// Commands for when Migration is brought down
}
}
上一篇:双转换为int转换为、int