可以说我有以下实体返回实体类型使用每个类型继承表时
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;
}
我不认为你可以。 – Yeonho
设计也有点味道;查询泛型类型的特定子类型,然后分支,可能应该用多态性代替。 – millimoose
在您评论的位置,来源已被提取。那是你想要阻止的吗?编辑:不,现在我明白了。现在思考时间。 – Michael