返回匿名类型的结果? [英] Return anonymous type results?
问题描述
使用下面的简单的例子,什么是返回使用LINQ to SQL从多个表结果的最佳方式?
Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?
说我有两个表:
Dogs: Name, Age, BreedId
Breeds: BreedId, BreedName
我要与他们的 BreedName
返回所有的狗。我应该使用这样的事情,没有任何问题让所有的狗:
I want to return all dogs with their BreedName
. I should get all dogs using something like this with no problems:
public IQueryable<Dog> GetDogs()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select d;
return result;
}
但是,如果我想与品种的狗,并尝试这个,我有问题:
But if I want dogs with breeds and try this I have problems:
public IQueryable<Dog> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result;
}
现在我认识到,编译器将不会让我回到了一套匿名类型,因为它的预期狗,但有什么办法,而无需创建一个自定义类型返回此?还是我创造我自己的 DogsWithBreedNames
类,并指定在选择这种类型的?还是有另一种更简单的方法?
Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type? Or do I have to create my own class for DogsWithBreedNames
and specify that type in the select? Or is there another easier way?
推荐答案
我倾向于去这个模式:
public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}
public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}
这意味着你有一个额外的类,但它的快速和容易code,易于扩展,可重用性和类型安全的。
It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.
这篇关于返回匿名类型的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!