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.
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. Collection navigation properties must implement ICollection<> of the target type.'
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
.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.