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

标签 .net entity-framework ef-code-first entity-framework-4

在 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/

相关文章:

c# - 检测 Async/Await 的滥用 : Prevent blocking calls

c# - connectionstring 和 entityframework 的问题

ios - 是否可以在 Monotouch/Xamarin 中实现 Entity Framework 的 Code First?

entity-framework - 首先在代码中定义与现有数据库的关系

C# 按钮仅在第二次单击时触发

c# - Xamarin -> System.Reflection.Assembly.GetExecutingAssembly 不起作用

c# - 更新数据库失败,因为它是只读的

entity-framework - Entity Framework : cross join causes OutOfMemoryException

entity-framework - EF Core 3 GroupBy 多列 Count Throws 与扩展但 linq 有效

c# - EF Code First 计算修改和创建的属性