简体   繁体   中英

Fluent configuration for base entity in Entity Framework

I have the following 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. Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration?

Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration?

No. You can configure base type validations and EF will apply them on derived types. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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