Ignore some inherited properties in EF6 code first

2019-08-03 07:36发布

问题:

I'm using EF6 code first with .NET4(I should deliver the project on win xp so I couldn't configure it with .NET4.5) in a win Form project.

I have a BaseEntity class that all other entities inherited from it:

public abstract class BaseEntity
{
    public int Id {get; set;}
    public int X {get; set;} 
    public int Y {get; set;} 
}  
public class Calendar:BaseEntity
{
    // properties    
}

How could I Ignore X,Y properties in my all entities without writing following code for each entity?

   modelBuilder.Entity<Calendar>()
            .Ignore(t => t.X)
            .Ignore(t => t.Y)

Note that I couldn't use [NotMapped] attribute because I'm using EF6 with .NET 4.

回答1:

Use EntityTypeConfigurations in stead of modelBuilder.Entity<>:

abstract class BaseEntityMapping : EntityTypeConfiguration<BaseEntity>
{
    public BaseEntityMapping()
    {
        this.Ignore(t => t.X);
        this.Ignore(t => t.Y);
    }
}

class CalendarMapping : BaseEntityMapping
{
    public CalendarMapping()
    {
        // Specific mappings
    }
}

And in OnModelCreating:

modelBuilder.Configurations.Add(new CalendarMapping());