Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

entity framework - An anonymous type cannot have multiple properties with the same name

I want to bind gridview through entity framework but it throws error like-

An anonymous type cannot have multiple properties with the same name Entity Framwrok

Here is my method.

public void UserList(GridView grdUserList)
{
    using (TreDbEntities context = new TreDbEntities())
    {

        var query =( from m in context.aspnet_Membership
                    from u in context.aspnet_Users
                    join usr in context.Users
                    on new { m.UserId, u.UserId } 
                    equals new { usr.MembershipUserID, usr.UserId }
                    into UserDetails
                    from usr in UserDetails
                    select new { 
                       CreationDate = m.CreateDate,
                       email = m.Email,
                       UserName = u.LoweredUserName,
                       Name = usr.FirstName + usr.LastNameLastName,
                       Active=usr.IsActive
                    }).ToList();
    }
}

It shows error here. usr.UserId.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The direct issue is in the anonymous type new { m.UserId, u.UserId }: the same name twice. You can fix that by giving explicit property names, for example: new { u1 = m.UserId, u2 = u.UserId }.

But then the next issue will be that both anonymous types that define the join will not have the same property names, so the final fix is this:

public void UserList(GridView grdUserList)
{
    using (TreDbEntities context = new TreDbEntities())
    {
        var query =( from m in context.aspnet_Membership
                    from u in context.aspnet_Users
                    join usr in context.Users
                    on new { u1 = m.UserId, u2 = u.UserId } 
                    equals new { u1 = usr.MembershipUserID, u2 = usr.UserId }
                    into UserDetails
                    from usr in UserDetails
                    select new { CreationDate = m.CreateDate,
                                 email = m.Email,
                                 UserName = u.LoweredUserName,
                                 Name = usr.FirstName + " " + usr.LastName,
                                 Active = usr.IsActive
                               }
                   ).ToList();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...