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

And*_*ndy 46 .net entity-framework entity-framework-4 ef-code-first

在Entity Framework Code First方法中,如何在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 ?
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*cey 24

随着Entity Framework 4.3的发布,您可以通过迁移实现此目的.

EF 4.3 Code First迁移演练

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法通过扩展`EntityTypeConfiguration`来做到这一点?例如,任何带Guid的东西都默认为`newsequentialid()`? (3认同)

Gav*_*tes 15

您可以通过类的构造函数设置默认值.这是我在当前项目中使用MVC3和Entity Framework 4.1的类:

namespace MyProj.Models
{
using System;
using System.Collections.Generic;

public partial class Task
{
    public Task()
    {
        this.HoursEstimated = 0;
        this.HoursUsed = 0;
        this.Status = "To Start";
    }

    public int ID { get; set; }
    public string Description { get; set; }
    public int AssignedUserID { get; set; }
    public int JobID { get; set; }
    public Nullable<decimal> HoursEstimated { get; set; }
    public Nullable<decimal> HoursUsed { get; set; }
    public Nullable<System.DateTime> DateStart { get; set; }
    public Nullable<System.DateTime> DateDue { get; set; }
    public string Status { get; set; }

    public virtual Job Job { get; set; }
    public virtual User AssignedUser { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)

  • 如果`HoursUsed`的数据库存储值是5.0,该怎么办?构造函数会覆盖数据库值吗?或者它将首先构造,然后用实际值替换默认值0? (11认同)

321*_*21X 7

我知道这个话题已经持续了一段时间,我走进了某种相同的问题.到目前为止,我无法找到一个解决方案,将整个事物放在一个地方,因此代码仍然可读.

在创建用户时,我希望通过对象本身设置一些字段private setters,例如GUID和创建日期,而不是"污染"构造函数.

我的用户类:

public class User
{
    public static User Create(Action<User> init)
    {
        var user = new User();
        user.Guid = Guid.NewGuid();
        user.Since = DateTime.Now;
        init(user);
        return user;
    }

    public int UserID { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
    public virtual ICollection<Widget> Widgets { get; set; }

    [StringLength(50), Required]
    public string Name { get; set; }
    [EmailAddress, Required]
    public string Email { get; set; }
    [StringLength(255), Required]
    public string Password { get; set; }
    [StringLength(16), Required]
    public string Salt { get; set; }

    public DateTime Since { get; private set; }
    public Guid Guid { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

来电代码:

context.Users.Add(User.Create(c=>
{
    c.Name = "Name";
    c.Email = "some@one.com";
    c.Salt = salt;
    c.Password = "mypass";
    c.Roles = new List<Role> { adminRole, userRole };
}));
Run Code Online (Sandbox Code Playgroud)


Yur*_*nko 4

不幸的是你不能。http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/a091ccd6-0ba8-4d4f-8f5e-aafabeb258e4

  • 您可以将默认值视为 Person 类的一部分。当您在数据库中设置默认值时,您将遇到以下问题:在保存实体之前,这些属性不会被初始化。当您生成 POCO 时,这是 DB First 和 Model First 中的问题。 (4认同)
  • 代码优先仍然是 CTP。如果您还没有为此编写一份 Connect 报告,请执行以下操作。 (3认同)
  • 好吧,我确实希望“仅代码”意味着一切都在代码中配置。在数据库中手动设置默认值不是一个好主意,因为我需要实体框架使用 context.CreateDatabase() 函数为我创建数据库,而且我真的不想同时维护代码和数据库脚本在同一时间。 (2认同)