【问题标题】:How set default value for a property using CodeFirst WITHOUT editing the generated migration?如何在不编辑生成的迁移的情况下使用 CodeFirst 为属性设置默认值?
【发布时间】:2016-09-11 14:47:21
【问题描述】:

我想为 POCO 类中的某些属性设置默认值。但是我宁愿不手动更改生成的迁移。

OnModelCreating 中是否有任何注释或命令可以为这些属性设置一些默认值?

【问题讨论】:

标签: c# entity-framework ef-code-first


【解决方案1】:

使用 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”的值。我尝试了多种方法,但都没有成功。

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 2011-10-29
    • 2011-05-21
    • 2020-05-26
    • 2018-11-23
    • 2017-05-27
    • 1970-01-01
    • 2021-07-15
    • 2012-02-23
    相关资源
    最近更新 更多