title: Entity Framework 5 adding existing entity to nested collection
body: <p>I've been trying to take advantage of a new way of creating many-to-many relationships - <a href="https://henriquesd.medium.com/entity-framework-core-5-0-many-to-many-relationships-52c6c8b07b6e" rel="nofollow noreferrer">nice article about EF 5 many-to-many relationships</a>.</p>
  <p>The article states that you no longer need to define relation class and the framework does the job for you.</p>
  <p>However, for a couple of hours now I've been struggling to add an existing entity to the collection of another entity.</p>
  <p>My models</p>
  <pre class="lang-cs prettyprint-override"><code>public record Bottle
  {
      [Key]
      public int Id { get; set; }
  
      [Required]   
      public string Username { get; set; }
  
      // some other properties
  
      public Collection&lt;User&gt; Owners { get; set; }
  }
  
  public record User
  {
      [Key]
      public int Id { get; set; }
  
      // some other properties
  
      public Collection&lt;Bottle&gt; Bottles { get; set; }
  }
  </code></pre>
  <p>Say that I want to add a new bottle to the database. I also know owners of that bottle. I had thought that this bit of code could work:</p>
  <pre class="lang-cs prettyprint-override"><code>public async Task&lt;int&gt; AddBottle(BottleForAddition bottle)
  {
      var bottleEntity = mapper.Map&lt;Bottle&gt;(bottle);
      bottleEntity.Owners = bottle
          .OwnerIds // List&lt;int&gt;
          .Select(id =&gt; new User { Id = id })
          .ToCollection(); // my extension method
  
      var createdEntity = await context.AddEntityAsync(bottleEntity);
      await context.SaveChangesAsync();
  
      return createdEntity.Entity.Id;
  }
  </code></pre>
  <p>but sadly it does not work (<code>BottleForAddition</code> is DTO with almost the same properties).</p>
  <p>I get this error:</p>
  <blockquote>
  <p>Unable to create bottle (error: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.</p>
  <p>Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'NOT NULL constraint failed: Users.Username'.</p>
  <p>at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)<br />
  at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()<br />
  at ...</p>
  </blockquote>
  <p>So I came up with this</p>
  <pre class="lang-cs prettyprint-override"><code>public async Task&lt;int&gt; AddBottle(BottleForAddition bottle)
  {
      var bottleEntity = mapper.Map&lt;Bottle&gt;(bottle);
      bottleEntity.Owners = (await context.Users
          .Where(u =&gt; bottle.OwnerIds.Contains(u.Id))
          .ToListAsync())
          .ToCollection();
  
      var createdEntity = await context.AddEntityAsync(bottleEntity);
  
      await context.SaveChangesAsync();
  
      return createdEntity.Entity.Id;
  }
  
  </code></pre>
  <p>That works but I have to fetch <code>User</code>s from the database.</p>
  <p>Do you know about a better way how to deal with it?</p>