1

使用 LINQ to SQL 和对象关系设计;假设我们有一个class Animal带有两个继承类的 a,namedCatDog。我们可以轻松加载“Animal”类及其属性:

var animals = from a in dataContext.Animals
              select a;

但是,当尝试加载Cator时Dog,dataContext 的属性既不是Cats也不是Dogs。如何使用自己的额外属性从表中加载 aCat或 a ?DogAnimal

提前致谢。

4

2 回答 2

2

投射到一只新猫或一只新狗身上:

猫:

var animals = from a in dataContext.Animals
              select new Cat {
                  CatProperty = a.Property
              };

狗:

var animals = from a in dataContext.Animals
              select new Dog {
                  DogProperty = a.Property
              };
于 2013-06-17T07:36:34.900 回答
2

使用OfType<T>

var dogs = from a in dataContext.Animals.OfType<Dog>()
              select a;

对于猫:

var cats = from a in dataContext.Animals.OfType<Cat>()
              select a;

就像这里显示的

...这里有一个完整的例子

于 2013-06-17T07:41:19.227 回答