Advertisement
otkalce

Entity Framework - many to many update

Apr 5th, 2023
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.64 KB | Source Code | 0 0
  1. // (1) Remove unused tags
  2. var toRemove = dbAudio.AudioTags.Where(x => !audio.Tags.Contains(x.Tag.Name));
  3. foreach (var srTag in toRemove)
  4. {
  5.     _dbContext.AudioTags.Remove(srTag);
  6. }
  7.  
  8. // (2) Add new tags
  9. var existingDbTagNames = dbAudio.AudioTags.Select(x => x.Tag.Name);
  10. var newTagNames = audio.Tags.Except(existingDbTagNames);
  11. foreach (var newTagName in newTagNames)
  12. {
  13.     var dbTag = _dbContext.Tags.FirstOrDefault(x => newTagName == x.Name);
  14.     // What if the tag doesn't exist at all?
  15.     if (dbTag == null)
  16.         continue;
  17.  
  18.     dbAudio.AudioTags.Add(new AudioTag
  19.     {
  20.         Audio = dbAudio,
  21.         Tag = dbTag
  22.     });
  23. }
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement