忽略EF CodeFirst中所有已实现的接口属性

本文关键字:实现 接口 属性 EF CodeFirst 忽略 | 更新日期: 2023-09-27 18:00:49

不久前,我在edmx模型中使用了DataBase-First方法。我创建了分部类来扩展edmx生成的域模型的功能。

//Generated by tt in edmx
public partial class DomainObject
{
    public int PropertyA {get; set;}
    public int PropertyB {get; set;}
}
//My own partial that extends functionality on generated one       
public partial class DomainObject: IDomainEntity
{
    public int EntityId {get; set;}
    public int EntityTypeId {get; set;}
    public int DoSomethingWithCurrentEntity()
    {
        //do some cool stuff
        return 0;
    }
}

所有部分都在实现接口IDomainEntity

public interface IDomainEntity
{
    int EntityId {get; set;}
    int EntityTypeId {get; set;}
    int DoSomethingWithCurrentEntity();
    //Another huge amount of properties and functions
}

因此,该接口中的所有属性都没有映射到数据库中的表

现在我已经迁移到代码优先方法,所有这些属性都试图映射到数据库。当然,我可以使用[NotMapped]属性,但接口和类中的属性数量巨大(超过300个(,并且还在继续增长。是否有任何方法可以同时忽略所有类的分部或接口中的所有属性。

忽略EF CodeFirst中所有已实现的接口属性

您可以使用反射来找出要忽略的属性,然后在DbContext.OnModelCreating方法中使用Fluent API忽略它们:

foreach(var property in typeof(IDomainEntity).GetProperties())
    modelBuilder.Types().Configure(m => m.Ignore(property.Name));