I have the following classes with a one-to-many relationship.
public class Category
{
public Category()
{
this.Products = new List<Product>();
}
public int Id {get;set;}
public string Name {get;set;}
public ICollection<Product> Products {get;set;}
}
public class Product
{
public int Id {get;set;}
public string Name {get;set;}
public int CategoryId {get;set;}
public Category Category {get;set;}
}
My datacontext is as shown below:
public class MyContext : DbContext
{
public virtual IDbSet<Category> Categories { get; set; }
public virtual IDbSet<Product> Products { get; set; }
}
I would like to replace the existing collectino products for the category with a new collection of categories. What is the best way to do this in EF?
Basically, from the provided collection, if productid is specified, update if the entity is not available, then add a new product. if not listed remove from the database.
Here is what I am trying to do.
using (var dbCtx = new MyDBEntities())
{
dbCtx.SaveChanges();
}
source
share