I am trying to insert a new entity (Product) with a generic method which works as expected. This entity (Product) has another entity (Supplier) and when I try to insert this same Product with a new Supplier related to it (aka Product.Suppliers.Add(NewSupplier)) it re-inserts an already present product (created with a seeder method) into the database... I know it has to do with the Supplier because when I don't add it and simply insert the Product and doesn't create a duplicate with the same supplier.
Here is more (simplified) information: Product Entity:
public class Product : BaseEntity
{
public string ProductName { get; set; }
public virtual ICollection<Supplier> Suppliers { get; set; }
... others
}
Supplier Entity:
public class Supplier:BaseEntity
{
public string SupplierName { get; set; }
public virtual ICollection<Product> Products { get; set; }
... others
}
I have a ProductSupplier table with SupplierId & ProductId using Fluent API. Can I still use my generic insert with this scenario, if yes how and what am I doing wrong, why is the Supplier I am getting from DB getting re-inserted?
Thank you all for any feedback! Kind regards
UPDATE: I think it is due to the fact that I encapsulate my context in a using statement when performing CRUD actions. I have come across THIS POST
I will take a look next week because I have to implement other functionalities. Feel free to add your 2cents meanwhile :)
UPDATE 2
This is my Generic insert method:
public static bool Insert<T>(T item) where T: class // here we specify that the <T> object is of type 'class'
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
ctx.Database.Log = (dbLog => logger.Debug(dbLog));
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
}