代码之家  ›  专栏  ›  技术社区  ›  renakre

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

  •  0
  • renakre  · 技术社区  · 5 年前

    我有以下代码,需要根据条件在导航属性中添加新项。 NotificationToUser 财产 Notification 班级是 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.invalidooperationexception:'导航属性的类型 实体类型“Notification”上的“ToUsers”是 “AppendPrepend1Iterator”未实现 收集。集合导航属性必须 实现目标类型的ICollection<gt;'

    通知类是:

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

    我想知道怎样才能减轻这个问题。

    0 回复  |  直到 5 年前
        1
  •  0
  •   Ryan    5 年前

    自从你 ToUsers IEnumerable<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();