【问题标题】:Adding a new item into navigation property causes "Collection navigation properties must > implement ICollection<> of the target type" error在导航属性中添加新项目会导致“集合导航属性必须 > 实现目标类型的 ICollection<>”错误
【发布时间】:2019-09-09 16:30:39
【问题描述】:

我有以下代码,我需要根据条件将新项目添加到导航属性中。 Notification 类的NotificationToUser 属性是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: '导航属性的类型 实体类型“通知”上的“ToUsers”是 'AppendPrepend1Iterator' 未实现 收藏。集合导航属性必须 实现目标类型的 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; }

}

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

【问题讨论】:

  • 显示Notification的来源。
  • 为什么地球上有人投票结束这个问题?!?!?!
  • @ChrisPratt 我添加了。
  • 异常告诉你具体做什么。 ToUsers 必须是 ICollection 才能用作导航属性,即 public ICollection&lt;NotificationToUser&gt; To Users { get; set; }
  • 此解决方案是否有替代方案?

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


【解决方案1】:

由于您的ToUsersIEnumerable&lt;NotificationToUser&gt; 类型,因此您需要在保存数据之前使用ToList()。在您的情况下,它是IQueryable&lt;NotificationToUser&gt;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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多