The type of the returned object when using a table for each type of inheritance

Suppose I have the following entities

public abstract class Animal { public int Id {get;set;} } public class Cat : Animal { } public class Dog : Animal { } 

Is it possible to determine the type of an object without creating an instance.

 var id = 1; var type = context.Animals.GetTypeOfAnimal(id) public static Type GetTypeOfAnimal(this ObjectSet<Animal> source, int id) { // What shall I do here, I dont want to fetch the instance at this point... var animal = source.First(a => a.Id == id); return animal.GetType(); } 

In one solution, I thought about using the following method ...

 public static Type GetTypeOfAnimal(this ObjectSet<Animal> source, int id) { var info = source.Where(a => a.Id == id).Select(a => new {IsDog = a is Dog, IsCat = a is Cat}).First(); if(info.IsDog) return typeof(Dog); if(info.IdCat) return typeof(Cat); return null; } 
+7
source share
1 answer

It is not possible to get this information without querying the database. You are using TPT - this means that the database contains tables Animal, Dog and Cat. Inheritance in the database is modeled through a one-to-one relationship between animals and a dog, as well as between animals and cats. The minimal thing you need to do is query both the Animal and Dog tables for this Id (it can exist in only one of them). The first problem is that you cannot directly access these tables using EF, because EF can only work with all objects (not just parts mapped to one table) - you must use direct SQL. The second problem is the fragility of this solution. If you add a new derived object, you must correct this query (the same thing happens for your example).

The reason TPT requests are slow is because EF needs to request the entire inheritance tree = in your case, Animal connected to Dog , combined to Animal , connected to Cat . There are some performance improvements in .NET 4.5 for querying the TPT inheritance tree, but that will not affect your query because it just needs to query the whole structure.

+2
source

All Articles