如何在 EF CF 中为 POCO 设置默认值? [英] How to set default value for POCO's in EF CF?

查看:20
本文介绍了如何在 EF CF 中为 POCO 设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Entity Framework Code First approach, 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 ?
    }
}

推荐答案

随着 Entity Framework 4.3 的发布,您可以通过迁移来做到这一点.

With the release of Entity Framework 4.3 you can do this through Migrations.

EF 4.3 代码第一次迁移演练

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

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

这篇关于如何在 EF CF 中为 POCO 设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆