读书人

Linq多对多查询

发布时间: 2013-09-08 15:21:21 作者: rapoo

Linq多对多查询求救
我这个需求是多对多 菜品和菜品分类 要根据菜品分类 查出所有菜品信息(包括菜品分类) 就是确定一条分类然后还要再加到查出每个菜品所有分类(这里的分类不止一个)代码如下:

var q = db.foodcategories.First(fc => fc.Id == categoryId);

var q_a = from qq in q.foods
from p in db.pictures
//from qfc in q_fc
where p.FoodId==qq.Id
select new FoodModel
{
Id = qq.Id,
Name = qq.Name,
pictureUrl=p.Url,
Price = qq.Price,
Description = qq.Description,
MainIngredient = qq.MainIngredient,
MinorIngredient = qq.MinorIngredient,
Flavoring = qq.Flavoring,
Discount = qq.Discount,
Recommended = qq.Recommended


,foodCategories = qq.foodcategories.Select(fc => new FCategoryModel { Name = fc.Name }).AsQueryable()
};

这样写会出现以下异常:There is already an open DataReader associated with this Connection which must be closed first. 求助解决方案 没有分了求大神帮忙,在线等 急急急 asp.net? linq asp.net 多对多
[解决办法]
这个提示说明你用到了DataReader但是没有正确关闭。和Linq无关。
[解决办法]
试试

var q = db.foodcategories.First(fc => fc.Id == categoryId);
var q_a = from qq in q.foods
join p in db.pictures on qq.Id equals p.FoodId
select new FoodModel
{
Id = qq.Id,
Name = qq.Name,
pictureUrl=p.Url,
Price = qq.Price,
Description = qq.Description,


MainIngredient = qq.MainIngredient,
MinorIngredient = qq.MinorIngredient,
Flavoring = qq.Flavoring,
Discount = qq.Discount,
Recommended = qq.Recommended,
foodCategories = qq.foodcategories.Select(fc => new FCategoryModel { Name = fc.Name }).AsQueryable()
};


[解决办法]
引用:
Quote: 引用:

试试

var q = db.foodcategories.First(fc => fc.Id == categoryId);
var q_a = from qq in q.foods
join p in db.pictures on qq.Id equals p.FoodId
select new FoodModel
{
Id = qq.Id,
Name = qq.Name,
pictureUrl=p.Url,
Price = qq.Price,


Description = qq.Description,
MainIngredient = qq.MainIngredient,
MinorIngredient = qq.MinorIngredient,
Flavoring = qq.Flavoring,
Discount = qq.Discount,
Recommended = qq.Recommended,
foodCategories = qq.foodcategories.Select(fc => new FCategoryModel { Name = fc.Name }).AsQueryable()
};

谢谢大神指教,能说明为什么这样就行,我那个就不行么?

我估计是inner join引起的吧, 你没写对,注意要对应,你可以测试一下,看看,顺便回馈我一下,
var q_a = from qq in q.foods
join p in db.pictures on qq.Id equals p.FoodId

读书人网 >.NET

热点推荐