C# Linq如何获取主记录和内部详细信息记录的特定字段
给定此类型的DB结构:C# Linq如何获取主记录和内部详细信息记录的特定字段,c#,linq,entity-framework-6,C#,Linq,Entity Framework 6,给定此类型的DB结构: Auction =0..N=> Bidders =0..N=> Bids 每个实体都有多个字段(例如拍卖名称、投标人名称、投标日期、投标金额等) 给定拍卖id,我想运行一个LINQ查询,一次提取: 拍卖的所有字段(通过其给定id) 最佳投标人的id和名称(忽略其他投标人的字段) 最佳投标人的最佳投标的id和金额(忽略其他投标的字段) 假设“最佳投标”是金额最高的投标,您可以构建一个LINQ到实体查询,查询该查询按降序按金额顺序订购投标,并首先(包含所有相关数
Auction =0..N=> Bidders =0..N=> Bids
每个实体都有多个字段(例如拍卖名称、投标人名称、投标日期、投标金额等)
给定拍卖id,我想运行一个LINQ查询,一次提取:
var result = (
from auction in db.Auctions
where auction.Id == auctionId
from bidder in auction.Bidders
from bid in bidder.Bids
orderby bid.Amount descending
select new
{
AuctionId = auction.Id,
AuctionTitle = auction.Title,
AuctionStartDate = auction.StartDate,
...,
IdOfTheBestBidder = bidder.Id,
NameOfTheBestBidder = bidder.Name,
IdOfTheBestBid = bid.Id,
AmountOfTheBestBid = bid.Amount,
}).FirstOrDefault();
对于所有拍卖,它都是类似的,但每个拍卖都有子查询:
var result = (
from auction in db.Auctions
from best in (from bidder in auction.Bidders
from bid in bidder.Bids
orderby bid.Amount descending
select new { bidder, bid }).Take(1)
select new
{
AuctionId = auction.Id,
AuctionTitle = auction.Title,
AuctionStartDate = auction.StartDate,
...,
IdOfTheBestBidder = best.bidder.Id,
NameOfTheBestBidder = best.bidder.Name,
IdOfTheBestBid = best.bid.Id,
AmountOfTheBestBid = best.bid.Amount,
}).ToList();
您可以使用两个linq查询,第一个查找最佳出价,如下所示
var biddersList= ( from bidder in db.Bidders
join bid in db.Bids
on bidder.Id equals bid.bidderId
where //Here you can give the conditions to select best bid of a bidder
group new { bidder, bid } by new { bidder.AuctionId } into bidandbidder
from grp in bidandbidder.DefaultIfEmpty()
select new {
grp.bidder.AuctionId,
grp.bidder.Id,
grp.bidder.Name,
grp.bid.Id,
grp.bid.Amount
}
);
在第二个linq查询中,使用biddersList
如下所示,通过给定的给定的拍卖\u Id
查找具有最佳投标人的最佳出价的拍卖详细信息
var auctionList = ( from ac in db.Auction
join bd in biddersList
on ac.Id equals bd.AuctionId
where ac.Id == given_auction_Id and //here you can give the conditions to select best bidder
select new{
// select fields
}
);
我建议使用实体作为财产(
new{Auction=Auction,BestBidder=best.bidder,BestBid=best.bide}
),而不是列出每一个财产。为了简洁起见,也不必在实体更新时更新代码。@只投影特定字段更平坦是OP的愿望。它最终可以应用于拍卖
,但导航属性修复可能会产生副作用。您所说的“导航属性修复”是什么意思?由于这将在数据库上运行(而不是在内存中),导航道具不应该在没有显式加载/包含的情况下自动工作吗?@Flater Yes,但是当查询结果具体化,并且投影包含完整的实体成员时,它将连接到上下文跟踪的其他相关实体对象(如果有)。例如,此技术用于模拟筛选的include.TIL:)尚未考虑到这一点,感谢您的详细说明!
var biddersList= ( from bidder in db.Bidders
join bid in db.Bids
on bidder.Id equals bid.bidderId
where //Here you can give the conditions to select best bid of a bidder
group new { bidder, bid } by new { bidder.AuctionId } into bidandbidder
from grp in bidandbidder.DefaultIfEmpty()
select new {
grp.bidder.AuctionId,
grp.bidder.Id,
grp.bidder.Name,
grp.bid.Id,
grp.bid.Amount
}
);
var auctionList = ( from ac in db.Auction
join bd in biddersList
on ac.Id equals bd.AuctionId
where ac.Id == given_auction_Id and //here you can give the conditions to select best bidder
select new{
// select fields
}
);