title: How to control EF Insert into database?
body: <p>I have 3 tables <code>Goods</code>, <code>Producer</code>, <code>Categories</code>. <code>Producer</code> and <code>Categories</code> have a one-to-many relationship with <code>Goods</code>, and I have a generic insert method, code shown below. </p>
  
  <p>The problem is that when I'm trying to insert a list of goods, first good is added correctly, but if the next one has a category with same id, it's throwing an exception about primary key.</p>
  
  <p>But I want to control insert something like, checking every time before insert tables <code>Categories</code> and <code>Producer</code> and if row already exists, just update it for example or skip. </p>
  
  <p>Code with models and my generic insert here:</p>
  
  <pre><code>public class Good
  {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int Id { get; set; }
      public string Name { get; set; }
      public decimal Price { get; set; }
  
      public virtual Category Category { get; set; }
      public virtual Producer Producer { get; set; }
  
      public override string ToString()
      {
          return Id + "/" + Name + "/" + Price + "/" + Category.Name + "/" + Producer.Name + "/" + Producer.Country;
      }
  }
  
  public class Producer
  {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int Id { get; set; }
      public string Name { get; set; }
      public string Country { get; set; }
  
      public virtual ICollection&lt;Good&gt; Goods { get; set; }
  
      public override string ToString()
      {
          return Id + "/" + Name + "/" + Country;
      }
  }
  
  public class Category
  {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int Id { get; set; }
      public string Name { get; set; }
  
      public virtual ICollection&lt;Good&gt; Goods { get; set; }
  
      public override string ToString()
      {
          return Id + "/" + Name;
      }
  }
  
  public void AddList(List&lt;T&gt; collection, DbContext GoodsContext)
  {
          foreach (var item in collection)
          {
              GoodsContext.Set&lt;T&gt;().Add(item);
              GoodsContext.SaveChanges();
          }
  }
  </code></pre>