using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; public static class LinqExtensions { public static void SyncJoinTable<TKey, Tdto, Tdb>( this DbSet<Tdb> target, IEnumerable<Tdto> dtoItems, Func<Tdto, TKey> selectDtoKey, IEnumerable<Tdb> dbItems, Func<Tdb, TKey> selectDbKey, Func<TKey, Tdb> selectNewEntity ) where Tdto: class where Tdb: class { /*--- Get IDs ---*/ var dbIds = dbItems.Select(selectDbKey).ToList(); var dtoIds = dtoItems.Select(selectDtoKey).ToList(); /*--- Add New Items ---*/ var newItems = dtoIds .Except(dbIds) .Select(selectNewEntity) .ToList(); target.AddRange(newItems); /*--- Remove Defunct Items ---*/ foreach (var dbItem in dbItems) { var itemKey = new List<Tdb>() { dbItem } .Select(selectDbKey) .FirstOrDefault(); if (!dtoIds.Contains(itemKey)) { target.Remove(dbItem); } } } }
myDbContext.UserRoles.SyncJoinTable( userDTO.Roles, x => x.Id, user.UserRoles, x => x.RoleId, x => new AppUserRole { RoleId = x, UserId = userDTO.Id } );
ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.