简体   繁体   中英

Entity Framework Code First CTP4 Default Column Values?

I have been looking into Code First with Entity Framework CTP4 and you can use the ModelBuilder to build up your table columns. Is there a way to set the default value for a column in the database using the ModelBuilder or some other mechanism?

Thank You!

I am using the constructor to set the default values. Never failed me

public class Activity
{
    [Required]
    public DateTime AddedDate { get; set; }

    public Activity()
    {
        AddedDate = DateTime.Now;
    }
}

在为迁移生成的代码中,您可以为列指定默认值:

AddColumn("users", "ReceiveSummaryEmail", c => c.Boolean(nullable: false, defaultValue: true));

This is my way, setting important properties with private setters in a creation method instead via the constructor

Model

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

Creation of new user

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

无法通过文本编辑器/应用程序找到添加默认值而不是手动编辑的方法这是实体框架中的错误...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM