PeteGO
PeteGO

Reputation: 5791

Entity Framework 4 and MVC 3 - Inheritence and Loading Derived Entities

I've got some common properties (CreatedBy, CreatedOn, UpdatedBy, UpdatedOn) for nearly all of my entities. I decided to have a BaseEntity with these properties and then have all of my other entities inherit from this one.

For example:

BaseEntity --> Question

BaseEntity --> Answer

Now how do I load questions from my model container?

There is no db.Questions or db.Answers any more. Just db.BaseEntities.

Specifically I want to load all questions by their subject - so normally I would say db.Questions.Where(q => q.Subject.Id.Equals(subjectId)).

How do I do this now?

Many thanks, Pete

Upvotes: 1

Views: 457

Answers (2)

Danny Varod
Danny Varod

Reputation: 18068

Do not use a base class for this.

You'll end up with one entity set and have to use typeof(X).

Worst of all, this may break future inheritance of other entities, especially if some are table per type, some are table per hierarchy and some are mixtures of the two.

Instead, use partial classes to define a common interface with the aspect properties (CreatedBy, CreatedOn, UpdatedBy, UpdatedOn).

Edit: The base entity will also require a table with the PKs of all your entities in it. This will cause the table to be unnecessarily large and may result in performance hits during queries and inserts.

Upvotes: 1

archil
archil

Reputation: 39501

First, there are multiple types of inheritance mapping strategies that you can use to configure your database

You can also add sets of concrete types to your DbContext

public class MyDbContext : DbContext
{
     public DbSet<Question> Questions { get; set; }
     public DbSet<Answer> Answers { get; set; }
}

And the most important - I would prefere composition over inheritance in your place. This feels more natural

public class HistoryRecord
{
    public User CreatedBy { get; set; }
    public User UpdatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
}

and use it as complex type inside Question, Answer, etc

public class Question
{
     public HistoryRecord HistoryRecord { get; set; }
}

Upvotes: 1

Related Questions