日期:2014-05-20 浏览次数:21126 次
List<ProductAttribute> list = from p in Product
join a in ProductAttribute
on p.Pid equals a.Pid
into temp
from t in temp.DefaultIfEmpty()
select new ProductAttribute
{
Pid = p.Pid,
PAid = t.Paid,
AttributeName = t.AttributeName
};
------解决方案--------------------
有事要出去,晚上回来帮你想办法。
要返回实体,在new里构造也是一条可行的办法。
------解决方案--------------------
直接:
var query = from p in db.Product
select new
{
p.Pid,
p.PName,
Attributes = db.ProductAttribute.Where(pa => pa.Pid == p.Pid)
};
foreach(var item in query)
{
string a = item.PName;
string b = item.Pid;
List<ProductAttribute> list = item.Attributes.ToList();
}
------解决方案--------------------
建关系
var query = db.ProductInfos.ToList().Select(t=>
new ProductResult
{
PName=t.PName,
Pid=t.ID,
list = t.ProductAttributeInfos
};
------解决方案--------------------
刚回家就看见你解决了问题,呵呵。恭喜,这也让我从中得到了锻炼。
我理解的你目标是这样:
假设有一个Product<Pid = 5>,然后把与之关联的所有Attribute作为一个内嵌的类,利用Product.Attributes直接访问到这组Attribute。
所以,我想在select 的new里,应该象之前我在4楼的回复一样,再有new或者子LINQ的查询,如同5楼的fangxinggood给出的答案一样。
而你在7楼的解决办法,正是因为LINQ to SQL返回的结果是IQueryable<>的,而不是LINQ to Objects的IEnumerable<>。而你之前声明的List<>是属于IEnumerable<>的,因此出现了错误。
这是我用Northwind做的一个模拟,其实List<>也是可以的,关键是接口类型的转换:
namespace LinqtoSql
{
class Program
{
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
List<Result> entities = (from s in db.Suppliers
join c in db.Customers
on s.City equals c.City
into temp
from t in temp.DefaultIfEmpty()
select new Result
{
SupplierName = s.CompanyName,
Custs = db.Customers.Where(c => c.City == t.City).ToList()
}).ToList<Result>();
foreach (Result r in entities)
{
Console.WriteLine("供应商<{0}>及其客户列表", r.SupplierName);
foreach (Customers c in r.Custs)
Console.WriteLine("\t{0}", c.ContactName);
}
}
}
class Result
{
public string SupplierName = string.Empty;
public List<Customers> Custs = null;
}