I'm using EF with code-first and I have models like this:
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public Customer ()
{
Products = new List<Product>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
// more stuff snipped...
public ICollection<Product> Products{ get; set; }
}
I am receiving a customer ID along with a list of product IDs. When the product doesn't exist in the DB, I want to add it:
var newProduct = new Product{ Id = id, Name = "<no name yet>", Customer = customer };
InsertProduct(newProduct);
The problem is that EF tries to cascade the changes and tries to insert a new Customer
object, with the same ID as an existing one, so it fails. How do I solve this?
This is the insert method:
public void InsertProduct(Product item)
{
CustomerContext.Entry(item).State = EntityState.Added;
CustomerContext.Set<Product>().Add(item);
}