Rob
Rob

Reputation: 225

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();

Upvotes: 0

Views: 754

Answers (1)

cdhowie
cdhowie

Reputation: 169038

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, })

Upvotes: 4

Related Questions