简体   繁体   English

实体框架中基本实体的流畅配置

[英]Fluent configuration for base entity in Entity Framework

I have the following BaseEntity 我有以下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; }
}

All my other entities derive from it. 我所有的其他实体都源自于此。 Now I'd like to use fluent configuration instead of the DataAnnotations. 现在,我想使用流畅的配置而不是DataAnnotations。 Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration? 我真的必须在每个DbModelBuilder配置中都配置两个字符串属性的MaxLength吗?

Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration? 我真的必须在每个DbModelBuilder配置中都配置两个字符串属性的MaxLength吗?

No. You can configure base type validations and EF will apply them on derived types. 可以。您可以配置基本类型验证,EF会将它们应用于派生类型。 For example: 例如:

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

Update (as per your comment): 更新(根据您的评论):

You can use the (rather new) Properties() method to define mapping and validations based on property names rather than on entity types. 您可以使用(而不是新的) Properties()方法基于属性名称而不是实体类型定义映射和验证。

For example: 例如:

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

See MSDN 参见MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM