title: Entity Framework how do I INSERT unique value on many to many relationship without having to do manual check
body: <p>Does anyone know how to insert unique values without explicitly having to check for an existing value?</p>
  
  <p>I am able to make this work, but I am less than impressed with the code I had to write. Basically I created a helper function to check a unique value on my container.</p>
  
  <p>The structure is pretty basic.</p>
  
  <p>[ Entry ] *&lt;----->* [ UniqueValue ]</p>
  
  <p><strong>Main code</strong></p>
  
  <pre><code>public static void ImportStuff ()
  {
      //Generate a list of importable items
      List&lt;DtoItems&gt; items = DtoItemGetter.GetItems();
      using( var container = new MyEntities() )
      {
          foreach( var item in items )
          {
              Entry newEntry = CreateNewEntry( item );
  
              //******** 
              // Here's the call to my helper method to check 
              // for the uniqueness of the values on the item I am importing
              //******** 
              item.UniqueValuesList.ForEach( 
                  uv =&gt; HelperMethod( container, newEntry, uv ) );
  
              containter.AddToEntries( newEntry );
  
              //Less important... but it would be nice if I didn't 
              // have to save everytime I add an new entry... but 
              // this necessary for the Helper check.
              container.SaveChanges();
          }
      }
  }
  </code></pre>
  
  <p><strong>Helper Method</strong></p>
  
  <pre><code>public static void HelperMethod( 
      MyEntities container, Entry newEntry, string checkValue )
  {
      UniqueItem unique = null;
  
      //Have to check to see if it already exists in the DB
      container.uniqueItems.ForEach( uv =&gt; { 
          if( uv.Name == checkValue )
          {
              unique = uv;
          } } );
  
      //Here's the money, either add the one I found, or 
      //create a new one... meh
      newEntry.UniqueItems.Add( 
          unique ?? new UniqueItem { Name = checkValue } );
  }
  </code></pre>
  
  <p>Hopefully this makes enough sense.</p>