Entity Framework Code First CTP4 Default Column Values?

倾然丶 夕夏残阳落幕 提交于 2019-12-05 17:39:12

问题


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!


回答1:


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




回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/4036705/entity-framework-code-first-ctp4-default-column-values

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