19

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.

4

2 回答 2

29

直接的问题是匿名类型new { m.UserId, u.UserId }:同名两次。您可以通过给出明确的属性名称来解决这个问题,例如:new { u1 = m.UserId, u2 = u.UserId }.

但接下来的问题将是定义连接的两个匿名类型将不具有相同的属性名称,因此最终修复是这样的:

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();
    }
}
于 2013-09-24T14:03:02.407 回答
11

@Gert 答案是正确的。只想展示更简单的解决方案 - 只给第一个 UserId 属性命名:

on new { MembershipUserID = m.UserId, u.UserId } 
于 2013-09-26T07:48:05.223 回答