【问题标题】:Fluent configuration for base entity in Entity Framework实体框架中基本实体的流畅配置
【发布时间】:2015-05-22 08:51:06
【问题描述】:

我有以下 BaseEntity

public class BaseEntity
{
    public BaseEntity()
    {
        DateCreated = DateTime.UtcNow;
        DateModified = DateTime.UtcNow;
    }

    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }

    [MaxLength(36)]
    public string CreateUserId { get; set; }

    [MaxLength(36)]
    public string ModifyUserId { get; set; }
}

我所有的其他实体都来源于它。现在我想使用流畅的配置而不是 DataAnnotations。我真的必须在每个 DbModelBuilder 配置中配置两个字符串属性的 MaxLength 吗?

【问题讨论】:

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


    【解决方案1】:

    我真的要配置两个字符串的MaxLength吗 每个 DbModelBuilder 配置中的属性?

    没有。您可以配置基本类型验证,EF 会将它们应用于派生类型。例如:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BaseEntity>().Property(x => x.CreateUserId).HasMaxLength(36);
        modelBuilder.Entity<BaseEntity>().Property(x => x.ModifyUserId).HasMaxLength(36);
    
        base.OnModelCreating(modelBuilder);
    }
    

    更新(根据您的评论):

    您可以使用(相当新的)Properties() 方法根据属性名称而不是实体类型定义映射和验证。

    例如:

    modelBuilder.Properties().Where(x => x.Name == "CreateUserId").Configure(x => x.HasMaxLength(36));
    modelBuilder.Properties().Where(x => x.Name == "ModifyUserId").Configure(x => x.HasMaxLength(36));
    

    MSDN

    【讨论】:

    • 是的,但我想摆脱 DataAnnotation
    • 现在我得到一个异常,BaseEntity 没有定义键。
    • @Sandro,请参阅我的修订版。我添加了Ignore&lt;BaseEntity&gt;()。假设您确实为派生类型定义了键,它应该可以正常工作。
    • 现在我回到 varchar(max) 来处理这些字段,因为在创建模型时会忽略 BaseEntity
    • 如果您使用 C# 6,您将能够使用 nameof 运算符避免“魔术字符串”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多