[英]Linq: An anonymous type cannot have multiple properties with the same name
How can i use GroupBy in linq expression using the same name?, I have the following code to get data from multiple entities.我如何在 linq 表达式中使用同名的 GroupBy?,我有以下代码从多个实体获取数据。 I have RP and SubParty tables both have a Name field and I want to display both but linq giving me the following error我有 RP 和 SubParty 表都有一个名称字段,我想同时显示这两个表,但 linq 给我以下错误
An anonymous type cannot have multiple properties with the same name一个匿名类型不能有多个同名的属性
var rp = await context.RP.AsNoTracking()
.Include(rp => rp.SubPartyNav)
.Include(rp => rp.partyNav)
.Where(rp => rp.ProductID == request.ID)
.GroupBy(rpSp => new
{
rpSp.partyNav.PartyName,
rpSp.SubPartyNav.PartyNav.PartyName })
.Select(r => new RspDTO
{
PartyName = r.Key.PartyName,
SubPartyName = r.Key.PartyName, })
.ToListAsync();
Just explicitly give the properties names:只需明确给出属性名称:
.GroupBy(rpSp => new
{
PartyName = rpSp.partyNav.PartyName,
SubPartyName = rpSp.SubPartyNav.PartyNav.PartyName })
.Select(r => new RspDTO
{
PartyName = r.Key.PartyName,
SubPartyName = r.Key.SubPartyName, })
Also, it looks more like you want .Distinct()
instead of .GroupBy()
, since you're only using the group key:此外,它看起来更像是你想要.Distinct()
而不是.GroupBy()
,因为你只使用组键:
.Select(rpSp => new
{
PartyName = rpSp.partyNav.PartyName,
SubPartyName = rpSp.SubPartyNav.PartyNav.PartyName })
.Distinct()
.Select(r => new RspDTO
{
PartyName = r.PartyName,
SubPartyName = r.SubPartyName, })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.