简体   繁体   中英

Ignoring all implemented interface properties in EF CodeFirst

Not so long ago I used DataBase First approach with edmx models. I've created partial classes to extend functionality of Domain Models generated by 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

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

Now I've migrate to Code First approach and all this properties are trying to map to 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. 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:

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

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