[英]Adding a new item into navigation property causes “Collection navigation properties must > implement ICollection<> of the target type” error
我有以下代码,需要根据条件在其中向导航属性添加新项。 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.InvalidOperationException:实体类型“ Notification”上的导航属性“ 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; }
}
我不知道如何减轻这个问题。
由于您的ToUsers
是IEnumerable<NotificationToUser>
类型,因此您需要在保存数据之前使用ToList()
。在您的情况下, Select
之后是IQueryable<NotificationToUser>
。
修改您的代码,如下所示:
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.