我有三张桌子,其中两张桌子有多对多关系。
照片:
这是中间mm表格中的数据:
修改 到了这里,我得到适当的4行,但它们都是相同的结果(我知道我需要4行,但结果不同)
return this._mediaBugEntityDB.LotteryOffers
.Find(lotteryOfferId).LotteryDrawDates
.Join(this._mediaBugEntityDB.Lotteries, ldd => ldd.LotteryId, lot => lot.Id, (ldd, lot) =>
new Lottery
{
Name = lot.Name,
CreatedBy = lot.CreatedBy,
ModifiedOn = lot.ModifiedOn
}).AsQueryable();
我的问题是,我如何通过多个表格检索所有彩票?我只提供LotteryOfferId?
我想要实现的是通过LotteryDrawDateId从彩票表中获取数据。
首先我使用LotteryOfferId从中间表获取DrawDates,并且通过中间表我得到drawDateIds以在LotteryDrawDate表中使用它们。从那张桌子我需要在LotteryDrawDate表中通过LotteryId来修复Lottey表。
我通过普通的SQL得到这个(LotteryOffersLotteryDrawDates是DB中的中间表,在模型中看不到):
选择 名称,Lotteries.CreatedBy,Lotteries.ModifiedOn,count(Lotteries.Id) 由Lotteries的TotalDrawDates加入Lotteries.Id的LotteryDrawDates = LotteryDrawDates.LotteryId在LotteryDrawDates.Id上加入LotteryOffersLotteryDrawDates = LotteryOffersLotteryDrawDates.LotteryDrawDate_Id 其中LotteryOffersLotteryDrawDates.LotteryOffer_Id = 19 group by 名称,Lotteries.CreatedBy,Lotteries.ModifiedOn
但Linq的故事不同:P
我想用lambda表达式来做这件事。 感谢
答案 0 :(得分:3)
db.LotteryOffer.Where(lo => lo.Id == <lotteryOfferId>)
.SelectMany(lo => lo.LotteryDrawDates)
.Select( ldd => ldd.Lottery )
.GroupBy( l => new { l.Name, l.CreatedBy, l.ModifiedOn } )
.Select( g => new
{
g.Key.Name,
g.Key.CreatedBy,
g.Key.ModifiedOn,
TotalDrawDates = g.Count()
} );
答案 1 :(得分:1)
你可以这样做:
var query = from lo in this._mediaBugEntityDB.LotteryOffers
where lo.lotteryOfferId == lotteryOfferId
from ld in lo.LotteryDrawDates
group ld by ld.Lottery into grp
select grp.Key;
我在查询语法中这样做,因为(在我看来)更容易看到发生了什么。重点是按Lottery
进行分组,因为您获得的LotteryDrawDates
个数Lottery
可以具有相同的LotteryDrawDates
。
如果您希望显示Lottery
每from lot in this._mediaBugEntityDB.Lotteries.Include(x => x.LotteryDrawDates)
where lot.LotteryDrawDates
.Any(ld => ld.LotteryDrawDates
.Any(lo => lo.lotteryOfferId == lotteryOfferId))
select lot
的计数,最好采用不同的方法:
Lottery
现在,您加载了LotteryDrawDates
个集合的lottery.LotteryDrawDates.Count()
个对象,之后您可以访问{{1}}而不会延迟加载异常。