【问题标题】:An anonymous type cannot have multiple properties with the same name一个匿名类型不能有多个同名的属性
【发布时间】:2013-09-24 09:58:11
【问题描述】:

我想通过实体框架绑定gridview,但是报错 喜欢-

一个匿名类型不能有多个属性同名的Entity Framwrok

这是我的方法。

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

这里显示错误。 usr.UserId。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    直接问题在匿名类型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();
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      on new { MembershipUserID = m.UserId, u.UserId } 
      

      【讨论】:

      • 可能的。唯一的问题是 imo 它使代码不那么自我解释,因为第一个 UserId 可能与MembershipUserID 无关。使用两个“匿名”名称表明属性只是占位符。
      • @GertArnold 首次使用 id 与会员资格有关 :) 它是 aspnet_Membership 表中的 id。另外我认为u1MembershipUserID 更不易于解释。我赞成你的回答,因此它也是完全正确的,它解释了错误的原因:)
      • 当然,完全不用担心!只是我喜欢我的代码显示强制执行相同的属性名称。也许只是口味问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多