简体   繁体   中英

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. I have RP and SubParty tables both have a Name field and I want to display both but linq giving me the following error

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:

        .Select(rpSp => new
        {
                PartyName = rpSp.partyNav.PartyName,
                SubPartyName = rpSp.SubPartyNav.PartyNav.PartyName })
        .Distinct()
        .Select(r => new RspDTO
        {
                PartyName = r.PartyName,
                SubPartyName = r.SubPartyName, })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM