I have following Insert method:
public static bool Insert<T>(T item) where T : class
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
try
{
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// ...
}
}
}
This works as expected but when i want to insert a new entity, which has a relation to a existing entity, EF is re-inserting this relational (already existing) entity again along with the new entity.
Details: I have a entity Supplier which already exists in my database. I want to insert a new entity Product which has this existing Supplier entity as relation so i retrieve this Supplier from the database and add it to this Product Entity. When i insert it using the generic method, it re-inserts this Supplier and obviously i don't want this behavior.
Am i doing something wrong here or is this by design and should i not use a generic insert function when having relational entities attached to my new entities?
Thank you for any suggestion or information! Kind regards
EDIT:
Product Entity:
// ... non relational properties
public ICollection<Price> Prices { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
public ICollection<Productnumber> ProductNumbers { get; set; }
Price Entity:
public Product Product { get; set; }
public Supplier Supplier { get; set; }
Supplier Entity:
public ICollection<Productnumber> ProductNumbers { get; set; }
public ICollection<Product> Products { get; set; }
public ICollection<Price> Prices { get; set; }
ProductNumber Entity:
public Supplier Supplier { get; set; }
public Product Product { get; set; }
How should i proceed to insert a new product? Is this possible having this structure and using a Generic insert?
If you want to add a new product to an existing Supplier you need to do as following:
1- Retrieve the supplier entity, let's call it sup
2- Add the new Product to it,
sup.Product = new Product{properties
...}
3- Update the supplier entity,
ctx.Entry(sup).State = EntityState.Modified;
ctx.SaveChanges();
You were adding a new supplier entity each time you were using the bool Insert<T> method
and this why you got unexpected behaviour, so just update the existing entry instead.
Hope this helps,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.