1

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 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

5 Comments

So, I have to create Mapping class for each entity. I'm looking for a solution that, I write one time and it works for all entities, if possible.
You will be better off having mapping classes per entity. It takes some time to create them, but after that, it will for ever be much easier to find a specific mapping if you want to inspect or modify it. Otherwise, I don't see any possibility. The only alternative is to convert the properties to get/set methods.
As an alternative(get/set methods), do you mean I change {get; set;} to get { return _field;} set { _field = value}?
Programming Entity Framework: DbContext By Julia Lerman, Rowan Miller, Chapter6: "It is possible to have properties in your class that do not map to the database. By con- vention, properties that do not have both a setter and a getter will not be part of the model. These are also known as transient properties.", so if I want have both set and get, I think this solution does not work.
I'm talking about methods: GetX(), SetX() etc. EF never maps methods. But it's a possible alternative. It may not work fir you if you need the properties X and Y for e.g. data binding. Then you better resort to mapping classes with a base class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.