简体   繁体   English

如何在 Entity Framework Core Fluent API 中将基本实体配置重构为单独的类

[英]How to refactor out base entity configurations to a separate class in Entity Framework Core Fluent API

I am porting over a website I maintain to .Net6 in the next few months.我将在接下来的几个月内将我维护的网站移植到 .Net6。 I have upgraded/updated the domain model and am now working on the Fluent API to define my EntityType Configurations.我已经升级/更新了域模型,现在正在使用 Fluent API 来定义我的 EntityType 配置。

There used to be a Properties method off modelBuilder where you could define your BaseEntity property configurations ONCE in the OnModelCreating method.曾经有一个关闭模型构建器的 Properties 方法,您可以在 OnModelCreating 方法中一次定义您的 BaseEntity 属性配置。 Apparently, that didn't make it into EF Core Fluent API.显然,这并没有进入 EF Core Fluent API。

Base entity class基本实体类

public abstract class EntityBase : IdBase, IEntity
{
    //private setter = immutable so it will only be created once   
    public DateTime DateCreated { get; private set; } = DateTime.UtcNow;      
    public string CreatedByUserId { get; private set; } = "";

    // use DateTime.UtcNow when modifying
    public DateTime DateModified { get; private set; } = DateTime.UtcNow;   
    public int ModifiedCount { get; private set; } = 0;           
    public string ModifiedByUserId { get; private set; } = "";
    public List<DomainEventBase> DomainEvents = new();
}

For example:例如:

modelBuilder.Properties().Where(x => x.Name == "CreatedByUserId").Configure(x => x.HasMaxLength(Common.Constants.GuidColumnLength));
modelBuilder.Properties().Where(x => x.Name == "ModifiedByUserId").Configure(x => x.HasMaxLength(Common.Constants.GuidColumnLength));
modelBuilder.Properties().Where(x => x.Name == "DateCreated").Configure(x => x.HasColumnType(Common.DateConstants.SqlDataTypeColumn));
modelBuilder.Properties().Where(x => x.Name == "DateModified").Configure(x => x.HasColumnType(Common.DateConstants.SqlDataTypeColumn));

Which I refactor out to a method called ConfigureBaseEntityProperties.我将其重构为一个名为 ConfigureBaseEntityProperties 的方法。

I am not finding a way to accomplish this in EF Core for .Net6.我没有找到在 EF Core for .Net6 中完成此操作的方法。 Ideally I would prefer to do it as EntityTypeConfiguration but I can't find a way to get that to work either.理想情况下,我更愿意将其作为 EntityTypeConfiguration 来执行,但我也找不到让它起作用的方法。

you can still do it like this:你仍然可以这样做:

foreach (var property in modelBuilder.Model.GetEntityTypes()
                .SelectMany(type => type.GetProperties())
                .Where(property => property.Name == "CreatedByUserId"))
{
     property.SetMaxLength(Common.Constants.GuidColumnLength);
}

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

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