将新项目添加到导航属性会导致“集合导航属性必须 > 实现目标类型的 ICollection<>”错误

ren*_*kre 3 c# asp.net entity-framework asp.net-core

我有以下代码,我需要根据条件将新项目添加到导航属性中。类的NotificationToUser属性NotificationIEnumerable类型。

  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();
Run Code Online (Sandbox Code Playgroud)

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

System.InvalidOperationException: '实体类型'通知'上的导航属性'ToUsers'的类型是'AppendPrepend1Iterator',它没有实现ICollection。集合导航属性必须实现目标类型的 ICollection<>。

通知类是:

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

}
Run Code Online (Sandbox Code Playgroud)

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

Rya*_*yan 5

由于您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();
Run Code Online (Sandbox Code Playgroud)