c# - 将新项目添加到导航属性会导致 "Collection navigation properties must > implement ICollection<> of the target type"错误

标签 c# asp.net entity-framework asp.net-core

我有以下代码,我需要根据条件将新项目添加到导航属性中。 NotificationToUser Notification 的属性(property)类(class)是 IEnumerable类型。

  Notification notification = new Notification
  {
      DateCreated = DateTime.Now,          
      ToUsers = _context.PeerGroupMemberships
         .Where(pg => pg.PeerGroup.SubmissionId == assessmentItem.SubmissionId && pg.UserId != currentUser.Id)                                       
         .Select(pg => new NotificationToUser { IsRead = false, UserId = pg.UserId })
  };


  if(submissionOwnerId != currentUser.Id)
  {
      notification.ToUsers = notification.ToUsers.Append(new NotificationToUser { IsRead = false, UserId = submissionOwnerId });
  }

  _context.Notifications.Add(notification);
  _context.SaveChanges();

但是,向导航属性添加新项目会导致此错误:

System.InvalidOperationException: 'The type of navigation property 'ToUsers' on the entity type 'Notification' is 'AppendPrepend1Iterator' which does not implement ICollection. Collection navigation properties must implement ICollection<> of the target type.'



通知类是:
public class Notification
{
    [Key]
    public int Id { get; set; }

    public string Text { get; set; }
    public string Url { get; set; }
    public DateTime DateCreated { get; set; }

    public IEnumerable<NotificationToUser> ToUsers { get; set; }

}

我想知道如何缓解这个问题。

最佳答案

由于您的 ToUsersIEnumerable<NotificationToUser>类型,您需要使用 ToList()在您保存数据之前。在您的情况下,它是 IQueryable<NotificationToUser>之后 Select .

修改你的代码如下:

if(submissionOwnerId != currentUser.Id)
{
  notification.ToUsers = notification.ToUsers
                         .Append(new NotificationToUser { IsRead = false, UserId = submissionOwnerId })
                         .ToList()
}else//for the situation you do not need to append new NotificationToUser 
{
 notification.ToUsers = notification.ToUsers.ToList()
}
_context.Notifications.Add(notification);
_context.SaveChanges();

关于c# - 将新项目添加到导航属性会导致 "Collection navigation properties must > implement ICollection<> of the target type"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857915/

相关文章:

c# - 在 WPF 中创建键绑定(bind)

c# - C# 类型的方法重载

c# - SqlDataReader "Enumeration yielded no results"

asp.net - 使用SetFocusOnError ="true"如何避免页面被刷新

entity-framework - EF 7 身份插入问题

c# - 有没有办法以 2-3 mbps 的速度使用串行端口?

c# - System.Web.Helpers.Crypto - 盐在哪里?

c# - 可以使用 EF 通过单个查询来查询我的案例吗? (实体的条件和嵌套实体的条件)

c# - Entity Framework 4.3.1 无法创建(/打开)数据库 [线程异常?]

c# - 获取模式之后没有类或 ID 的文本