Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in .Net EntityFramework 4.0 for similar database tables

I am looking for a solution in the following problem:

I have many tables that differentiate from one another in few/none columns (Why this happens is not the case as I have not designed said database nor can I change it).

Example: Table User: Columns{name,surname,age} Table OldUser: Columns(name,surname,age,lastDateSeen} etc

Is there any way to indicate to the EntityFramework 4.0 in Visual Studio to extend a base class consisting of _name,_surname,_age fields and their corresponding properties so that I can use that class for batch jobs in the code?

My current solution is to make this class and use converters to pass the values from the persistent objects its' objects. It works but it is not elegant and I don't like it.

I come from a java/hibernate environment where this is basic functionality.

(for future refernce can the same thing be done if I want the classes to implement an interface?)

Thanks in advance.

like image 238
Athanasios Kataras Avatar asked Dec 18 '12 12:12

Athanasios Kataras


1 Answers

Since your RDBMS (at least SQL Server 2008 and older) doesn't allow for table inheritance, I would recommend that you do not use inheritance in the DB model in C#. This is especially recommended when you cannot control the design of the tables.

Instead use an interface if you actually have clients of those classes who will benefit from the abstraction, but not being able to control the design of the DB makes this less valuable because the DB designer could change the tables thereby making your EF classes no longer implement the interface:

public interface IUser {
  public string Name { get; }
  // etc...
}

public class User : IUser {
  public string Name { get; set; }
  // etc...
}

public class OldUser : IUser {
  public string Name { get; set; }
  // rest of IUser
  public DateTime? LastSeenOn { get; set; }
}
like image 129
Josh Kodroff Avatar answered Oct 19 '22 14:10

Josh Kodroff