Entity Framework Code First CTP4 Default Column Values?

人盡茶涼 提交于 2019-12-04 01:01:46

Couldn't find a way to add default value other than manualy edit via text editor / application This is a bug in the Entity Framework...

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

In the code generated for a migration, you can specify a default value for a column:

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 };
}));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!