简体   繁体   English

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

[英]Adding a new item into navigation property causes “Collection navigation properties must > implement ICollection<> of the target type” error

I have the following code, where I need to add a new item into the navigation property depending on the condition. 我有以下代码,需要根据条件在其中向导航属性添加新项。 NotificationToUser property of Notification class is IEnumerable type. 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();

However, adding a new item to the navigation property causes this error: 但是,将新项目添加到导航属性会导致此错误:

System.InvalidOperationException: 'The type of navigation property 'ToUsers' on the entity type 'Notification' is 'AppendPrepend1Iterator' which does not implement ICollection. System.InvalidOperationException:实体类型“ Notification”上的导航属性“ ToUsers”的类型为“ AppendPrepend1Iterator”,它没有实现ICollection。 Collection navigation properties must implement ICollection<> of the target type.' 集合导航属性必须实现目标类型的ICollection <>。

The Notification class is: 通知类是:

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

}

I wonder how I can mitigate this issue. 我不知道如何减轻这个问题。

Since your ToUsers is IEnumerable<NotificationToUser> type, you need to use ToList() before you save the data.In your situation,it is IQueryable<NotificationToUser> after Select . 由于您的ToUsersIEnumerable<NotificationToUser>类型,因此您需要在保存数据之前使用ToList() 。在您的情况下, Select之后是IQueryable<NotificationToUser>

Modify your code as follow: 修改您的代码,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM