简体   繁体   English

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

[英]Ignoring all implemented interface properties in EF CodeFirst

Not so long ago I used DataBase First approach with edmx models. 不久前,我使用了DataBase First方法和edmx模型。 I've created partial classes to extend functionality of Domain Models generated by edmx. 我创建了部分类来扩展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;
    }
}

All partials were implementing interface IDomainEntity 所有部分都在实现接口IDomainEntity

public interface IDomainEntity
{
    int EntityId {get; set;}
    int EntityTypeId {get; set;}
    int DoSomethingWithCurrentEntity();

    //Another huge amount of properties and functions
}

So all properties from this interface were not mapped to tables in DataBase 因此,此接口中的所有属性都未映射到DataBase中的表

Now I've migrate to Code First approach and all this properties are trying to map to DataBase. 现在我已迁移到Code First方法,所有这些属性都试图映射到DataBase。 Of course I could use [NotMapped] attribute but amount of properties in interface and classes is huge (more than 300) and continuing to grow further. 当然我可以使用[NotMapped]属性,但接口和类中的属性数量很大(超过300)并且继续增长。 Is there any approach to ignore all properties from partial or interface for all classes at once. 是否有任何方法可以同时忽略所有类的部分或接口的所有属性。

You can use reflection to find out which properties to ignore, then ignore them with Fluent API in DbContext.OnModelCreating method: 您可以使用反射来找出要忽略的属性,然后在DbContext.OnModelCreating方法中使用Fluent API忽略它们:

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

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

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