【问题标题】:Adding to ICollection of type entity issue添加到类型实体问题的 ICollection
【发布时间】:2013-03-28 08:43:29
【问题描述】:

有人可以帮忙吗 不知道我用错了什么:

在我的控制器中:

 [HttpPost]
 public ActionResult SaveRecommendedUserDetails(RecommendAFriendViewModel model)
 {
    //List<Entities.Group.Group> entityGroups = new List<Entities.Group.Group>();

        foreach (var group in model.Groups)
        {
          Entities.Group.Group entityGroup = new Entities.Group.Group();
          entityGroup.GroupId = group.GroupId;
          //entityGroups.Add(entityGroup);
          recommendedUser.Groups.Add(entityGroup); //groups in recommendeduser is already of type ICollection.
        }
 }

RecommendAFriendViewModel 模型组属性:

 public IEnumerable<DataModels.Group.GroupDataModel> Groups { get; set; }

RecommendedUser 实体 Groups 属性:

  public virtual ICollection<Group.Group> Groups { get; set; }

在我得到的两条红线上:无法从“int”转换为“Zinc.Entities.Group.Group”
和: system.Collections.Generic.List.Add(Zinc.Entities.Group.Group)' 的最佳重载方法匹配有一些无效参数

可以告诉我我做错了什么吗? 谢谢

【问题讨论】:

    标签: asp.net-mvc-3 entities icollection


    【解决方案1】:

    您从未初始化过entityGroups 变量。在使用变量之前,您应该确保它已被分配。您的entityGroup 的范围也可以移动到foreach 循环:

    [HttpPost]
    public ActionResult SaveRecommendedUserDetails(RecommendAFriendViewModel model)
    {
        var entityGroups = new List<Entities.Group.Group>();
        foreach (var group in model.Groups)
        {
            if (!recommendedUser.Groups.Any(x => x.GroupId == group.GroupId))
            {
                var entityGroup = new Entities.Group.Group();
                entityGroup.GroupId = group.GroupId;
                entityGroups.Add(entityGroup.GroupId);
            }
        }
        recommendedUser.Groups.Add(entityGroups);
    }
    

    【讨论】:

    • 感谢我将一行移到 foreach 中并将 ICollection 更改为 List 但在推荐用户.Groups.Add(entityGroups) 上仍然出现红线;即使在我移动了新的 Entities.Group.Group(); 之后,与另一条红线相同的“错误”;进入foreach
    • recommendedUser 是什么?我看不到你在任何地方声明这个变量。
    • 当您尝试使用我的代码时收到什么编译错误消息?
    • 'System.Collections.Generic.ICollection.Add(Zinc.Entities.Group.Group)' 的最佳重载方法匹配有一些无效参数无法从System.Collections.Generic.List' 到 'Zinc.Entities.Group.Group'
    • 您在我的回答中在哪里看到ICollection?请再仔细阅读我的回答。
    【解决方案2】:

    您没有在 foreach 循环的每次迭代中实例化一个新的 Entities.Group.Group 对象。您所做的只是覆盖最后一个 entityGroup.GroupId 属性集,然后尝试将相同的实体对象添加到集合中,因为它已经存在于之前的迭代中。

    if 语句中移动你的 entityGroup 变量声明应该可以解决你的问题。

    if (!recommendedUser.Groups.Any(x => x.GroupId == group.GroupId))
    {
      Entities.Group.Group entityGroup = new Entities.Group.Group(); // here
      entityGroup.GroupId = group.GroupId;
      entityGroups.Add(entityGroup); //get red line here
    }
    

    【讨论】:

    • 非常感谢,但我仍然在 .add 行上得到红线,说明最佳重载方法匹配..有一些无效参数
    • 哦,呃,我刚刚注意到您正在尝试将 GroupId 添加到 Group 对象的集合中。您只想添加 entityGroup 对象 - 我更新了我的示例
    猜你喜欢
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2011-12-10
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多