C# 这个长查询的简短查询
有谁能告诉我最短的查询:C# 这个长查询的简短查询,c#,linq-to-sql,C#,Linq To Sql,有谁能告诉我最短的查询: var guestpartyids = db.CeremonyGuestParties.Where(p => p.CeremonyId == id) .Select(p => p.GuestPartyId); List<GuestParty> guestparties = new List<GuestParty>(); foreach
var guestpartyids = db.CeremonyGuestParties.Where(p => p.CeremonyId == id)
.Select(p => p.GuestPartyId);
List<GuestParty> guestparties = new List<GuestParty>();
foreach (var party in guestpartyids)
{
guestparties.Add(db.GuestParties.Single(p => p.Id == party));
}
var guestpartyids=db.CeremonyGuestParties.Where(p=>p.CeremonyId==id)
.选择(p=>p.GuestPartyId);
List guestparties=新列表();
foreach(guestpartyids中的var方)
{
Add(db.guestparties.Single(p=>p.Id==party));
}
这应该可以
guestparties.AddRange(
from cgp in db.CeremonyGuestParties
where cgp.CeremonyId == id
join gp in db.GuestParties on cgp.GuestPartyId equals gp.Id
select gp
);
请注意,这将导致一个数据库调用,因为您的代码将导致1+N查询。但它不能像Single()那样确保只有一个匹配ID。无论如何,这应该在数据库上强制执行,而不是在代码中强制执行。如何:
List<GuestParty> guestparties = from cgp in db.CeremonyGuestParties.
Where cgp.CeremonyId .id == id)
select cgp.Guestparties.ToList();
List guestparties=来自db.CeremonyGuestParties中的cgp。
其中cgp.CeremonyId.id==id)
选择cgp.Guestparties.ToList();