问题
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