假设我有以下实体
public abstract class Animal
{
public int Id {get;set;}
}
public class Cat : Animal
{
}
public class Dog : Animal
{
}
是否可以在不创建实例的情况下确定实体的类型。
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();
}
我考虑过使用以下方法的一种解决方案...
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;
}