Simulating Multiple Table Inheritance in Linq-to-SQL
By now, everyone knows that Linq-to-SQL does not natively support multiple table inheritance (a.k.a., table-per-subtype) and that you can use other ORM frameworks such as the Entity 开发者_开发百科Framework, NHibernate, etc. instead if you want native support for multiple table inheritance (reference the SO question "Multiple Inheritance in LINQtoSQL" if you have any doubts).
However, supposing that you did want to use (or were limited to use) Linq-to-SQL as your ORM layer, has anyone identified a simple and straight-forward design strategy for simulating multiple table inheritance in Linq-to-SQL projects so that client code can be written against the Linq-to-SQL layer using a natural, object-oriented API?
I think Sam had the good answer : Linq2Sql doesn't seems to be able to do that. But as long as you just want to simulate this behavior, I would do something like that:
/// <summary>
/// Declare POCO (Plain Old CLR Object) as you would to manipulate your inheritance
/// </summary>
public class Person
{
public abstract void Load();
public abstract void Save();
}
/// <summary>
/// Simulate a consistent behavior
/// </summary>
public class Customer : Person
{
public override void Load()
{
// - Do some Linq2Sql stuff
}
public override void Save()
{
// - Do some Linq2Sql stuff
}
}
For queries like "JOIN", I would consider generating my own expression trees, if I really need this, cause this quickly becomes tricky. The "Left Outer Join" method you see in this example by hajirazin could also be put "protected" in class Person and called with right values from "Customer" and other children.
In conclusion, I think all the work has to be done manually to simulate requests in Objects. Expression trees could do everything but it is difficult to finalize.
Best regards,
精彩评论