efcore 实体配置,GetEntityTypes:使用.Property< TEntity>的通用版本来配置实体属性。在EF Core中...

In my EF core project I have a few entities that inherit from a base class DBEntity:

public abstract class DBEntity

{

public int Id { get; set; }

public DateTime CreatedOn { get; set; }

public DateTime UpdatedOn { get; set; }

public EntityStatus EntityStatus { get; set; }

}

I want to set some specific properties with default value for every entity that inherits from DBEntity. Currently I'm using this code:

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

var entities = modelBuilder.Model

.GetEntityTypes()

.Where(w => w.ClrType.IsSubclassOf(typeof(DBEntity)))

.Select(p => modelBuilder.Entity(p.ClrType));

foreach (var entity in entities)

{

entity

.Property("CreatedOn")

.HasDefaultValueSql("GETDATE()");

entity

.Property("UpdatedOn")

.HasComputedColumnSql("GETDATE()");

entity

.Property("EntityStatus")

.HasDefaultValue(EntityStatus.Created);

}

}

This works fine but I don't want to specify property names using string constants (bad for refactoring etc.).

Is there a way to loop through entities that inherit from DBEntity and use property expression to configure default values like this:

foreach (var entity in entities)

{

entity

.Property(k => k.CreatedOn)

.HasDefaultValueSql("GETDATE()");

// ....

}

Important constraint: I cannot directly call modelBuilder.Entity().Property(k => k.CreatedOn) because it will mess up all tables.

解决方案

As pointed out in the comments, you can simply replace the string constants with nameof(DBEntity.CreatedOn) etc.

But if you want to work with typed accessors, you can move the base entity configuration code to a generic method (with the generic argument being the actual entity type) and call it via reflection.

For instance, add the following to your DbContext derived class:

static void ConfigureDBEntity(ModelBuilder modelBuilder)

where TEntity : DBEntity

{

var entity = modelBuilder.Entity();

entity

.Property(e => e.CreatedOn)

.HasDefaultValueSql("GETDATE()");

entity

.Property(e => e.UpdatedOn)

.HasComputedColumnSql("GETDATE()");

entity

.Property(e => e.EntityStatus)

.HasDefaultValue(EntityStatus.Created);

}

and then use something like this:

var entityTypes = modelBuilder.Model

.GetEntityTypes()

.Where(t => t.ClrType.IsSubclassOf(typeof(DBEntity)));

var configureMethod = GetType().GetTypeInfo().DeclaredMethods.Single(m => m.Name == nameof(ConfigureDBEntity));

var args = new object[] { modelBuilder };

foreach (var entityType in entityTypes)

configureMethod.MakeGenericMethod(entityType.ClrType).Invoke(null, args);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值