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

问题描述

在实体框架4,code只(CTP3),你怎么在POCO的EntityConfiguration类中的属性设置默认值?

 公共类Person
{
    公众诠释编号{获得;组; }
    公共字符串名称{;组; }
    公开日期时间CreatedOn {获得;组; }
}

公共类PersonConfiguration:EntityConfiguration<人>
{
    公共PersonConfiguration()
    {
        物业(P => p.Id).IsIdentity();
        属性(p值=> p.Name).HasMaxLength(100);

        //为CreatedOn设置默认值?
    }
}
 

解决方案

通过实体框架4.3的版本中,您可以通过迁移做到这一点。

<一个href="http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-$c$c-based-migrations-walkthrough.aspx">EF 4.3 code首先迁移演练

因此​​,使用你的榜样,它会是这样的:

 公共部分类AddPersonClass:DbMigration
{
    公众覆盖无效向上()
    {
        CREATETABLE(
            人,
            C =&GT;新
                {
                    n = c.Int(可空:假的,身份:真)
                    名称= c.String(最大长度:100)
                    CreatedOn = c.DateTime(可空:假的,设置defaultValue:DateTime.UtcNow)
                })
            .PrimaryKey(T =&GT; 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
    }
}

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

09-05 01:14