gpt4 book ai didi

.net - 如何在 EF CF 中设置 POCO 的默认值?

转载 作者:行者123 更新时间:2023-12-03 06:18:56 34 4
gpt4 key购买 nike

在 Entity Framework 代码优先方法中,如何为 POCO 的 EntityConfiguration 类中的属性设置默认值?

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 ?
}
}

最佳答案

随着 Entity Framework 4.3 的发布,您可以通过迁移来完成此操作。

EF 4.3 Code First Migrations Walkthrough

所以使用你的例子,它会是这样的:

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
}
}

关于.net - 如何在 EF CF 中设置 POCO 的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3137738/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com