implement ICollection<> of the target type"错误-6ren"> implement ICollection<> of the target type"错误-我有以下代码,我需要根据条件将新项目添加到导航属性中。 NotificationToUser Notification 的属性(property)类(class)是 IEnumerable类型。 -6ren">
gpt4 book ai didi

c# - 将新项目添加到导航属性会导致 "Collection navigation properties must > implement ICollection<> of the target type"错误

转载 作者:行者123 更新时间:2023-12-04 02:44:21 25 4
gpt4 key购买 nike

我有以下代码,我需要根据条件将新项目添加到导航属性中。 NotificationToUser Notification 的属性(property)类(class)是 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: 'The type of navigation property 'ToUsers' on the entity type 'Notification' is 'AppendPrepend1Iterator' which does not implement ICollection. Collection navigation properties must implement ICollection<> of the target type.'



通知类是:
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; }

}

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

最佳答案

由于您的 ToUsersIEnumerable<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();

关于c# - 将新项目添加到导航属性会导致 "Collection navigation properties must > implement ICollection<> of the target type"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com