【发布时间】:2016-09-11 14:47:21
【问题描述】:
我想为 POCO 类中的某些属性设置默认值。但是我宁愿不手动更改生成的迁移。
OnModelCreating 中是否有任何注释或命令可以为这些属性设置一些默认值?
【问题讨论】:
-
请不要混淆表示层asp.net-mvc框架和数据访问entity-framework:)
标签: c# entity-framework ef-code-first
我想为 POCO 类中的某些属性设置默认值。但是我宁愿不手动更改生成的迁移。
OnModelCreating 中是否有任何注释或命令可以为这些属性设置一些默认值?
【问题讨论】:
标签: c# entity-framework ef-code-first
使用 EF6,可以在 FluentAPI 的 OnModelCreating 方法中配置属性值。 假设我有 User 类,并且我希望 Country 属性始终为 USA。
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
public class Context : DbContext
{
public DbSet<User> Users {get; set;}
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Properties().Where(p => p.Name == "Country").Configure(x => x.ClrPropertyInfo.SetValue(currentInstanceOfUser, "USA"));
}
}
您需要在上面的代码中传递“currentInstanceOfUser”的值。我尝试了多种方法,但都没有成功。
【讨论】: