使用下面的简单示例,使用 Linq to SQL 从多个表返回结果的最佳方式是什么?
假设我有两个表:
Dogs: Name, Age, BreedId
Breeds: BreedId, BreedName
我想返回所有带有 BreedName
的狗。我应该让所有的狗都使用这样的东西没有问题:
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;
}
但是如果我想要品种的狗并尝试这个我有问题:
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;
}
现在我意识到编译器不会让我返回一组匿名类型,因为它期待 Dogs,但是有没有办法在不必创建自定义类型的情况下返回它?或者我是否必须为 DogsWithBreedNames
创建自己的类并在选择中指定该类型?或者还有其他更简单的方法吗?
最佳答案
我倾向于采用这种模式:
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;
}
这意味着您有一个额外的类,但它可以快速轻松地编写代码、易于扩展、可重用且类型安全。
关于c# - 返回匿名类型的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/534690/