Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand your problem correcly, the <code>genres</code> collection contains all the <code>Genre</code> objects that should be in the <code>Band</code> genre list as a result of running the <code>UpdateBandGenres</code> method (and not just the list to add or list to delete). In that case the simplest would be removing all the genres from the collection and adding all the genres with the <code>Guid</code>s from your <code>genres</code> collection.</p> <p>First of all, you don't need joins to grab your <code>newGenres</code>:</p> <pre><code>var newGenres = ctx.Genres.Where(g =&gt; genres.Contains(g.GenreId)); </code></pre> <p>Secondly, you need to fetch the <code>Band</code> object, since modifying its <code>Genres</code> collection will tell EF to modify the <code>BandGenres</code> table in SQL:</p> <pre><code>Band band = ctx.Bands.SingleOrDefault(b =&gt; b.BandId == bandId); </code></pre> <p>After that you can clear the <code>band.Genres</code> collection and add the <code>newGenres</code> on top. As a result you code will look like:</p> <pre><code>public void UpdateBandGenres(Guid bandId, IEnumerable&lt;Guid&gt; newGenreIds) { using (var ctx = new OpenGroovesEntities()) { List&lt;Genre&gt; newGenres = ctx. Genres. Where(g =&gt; newGenreIds.Contains(g.GenreId)). ToList(); Band band = ctx.Bands.Single(b =&gt; b.BandId == bandId); band.Genres.Clear(); newGenres.ForEach(band.Genres.Add); ctx.SaveChanges(); } } </code></pre> <p>Btw, I'd also recommend being consistent with naming your variables - e.g. <code>IEnumerable&lt;Guid&gt; genres</code> might be a bit misleading, since it's actually a collection of <code>Guid</code>s, and not a collection of <code>Genre</code> objects. Therefore I named it <code>newGenreIds</code> to be consistent with your <code>Guid bandId</code> variable name.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload