C#C
C#3y ago
DarkVader

✅ Remove many to many with select

So here is the code snippet,
var post = await _ctx.Posts
            .Include(x => x.LikedBy)
            .Include(x => x.DislikedBy)
            .Include(x => x.SeenBy)
            .Select(x => new PostDo
            {
                Id = x.Id,
                IsLiked = x.LikedBy.Any(x => x.Id == _userId),
                IsDisliked = x.DislikedBy.Any(x => x.Id == _userId),
                IsSeen = x.SeenBy.Any(x => x.Id == _userId),
                LikedBy = x.LikedBy.Where(x => x.Id == _userId).ToList(),
                DislikedBy = x.DislikedBy.Where(x => x.Id == _userId).ToList(),
                SeenBy = x.SeenBy.Where(x => x.Id == _userId).ToList(),
            })
            .FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
post.DisliekdBy.Remove(user);
_ctx.Posts.Update(post); // This is not updating property DislikedBy
await _ctx.SaveChangesAsync(cancellationToken) > 0;

If I add something to any of the Lists LikedBy, DislikedBy and SeenBy they are added, but if I remove, they are not removed
I read the docs and I know that LikedBy, DislikedBy and SeenBy are not tracked, but I honestly cant find any smart way of doing this except pulling all of the LikedBy, DislikedBy and SeenBy but that is memory inefficient and I have multiple DB calls, so is there something like this only for lists
using var context = new BlogsContext();
var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog");

// Change a property value
context.Entry(blog).Property(e => e.Name).CurrentValue = ".NET Blog (Updated!)";

// Add a new entity to the DbContext
context.Add(
    new Post
    {
        Blog = blog,
        Title = "What’s next for System.Text.Json?",
        Content = ".NET 5.0 was released recently and has come with many..."
    });

Console.WriteLine(context.ChangeTracker.DebugView.LongView);
Was this page helpful?