【发布时间】: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<NotificationToUser> To Users { get; set; }。 -
此解决方案是否有替代方案?
标签: c# asp.net entity-framework asp.net-core