asp.net mvc - Many to many insert with repository Entity Framework -
my entities:
public class product : base.baseentity { public product() { this.colors = new hashset<color>(); } [stringlength(50)] public string productname { get; set; } public int categoryid { get; set; } [stringlength(100)] public string stockfinishes { get; set; } [stringlength(50)] public string guarantee { get; set; } [stringlength(50)] public string installation { get; set; } public virtual productentity.category ownercategory { get; set; } public virtual ilist<variationentity.variation> variations { get; set; } public virtual icollection<productentity.color> colors { get; set; } } public class color : base.baseentity { public color() { this.products = new hashset<product>(); } [stringlength(50)] public string colorname { get; set; } public virtual icollection<productentity.product> products { get; set; } } my controller:
[httppost] public actionresult newproduct(models.dto.productdto.productvm productmodel) { if (modelstate.isvalid) { data.models.orm.entity.productentity.product productentity = new data.models.orm.entity.productentity.product(); productentity.productname = productmodel.productname; productentity.createdby = user.userid; productentity.categoryid = productmodel.categoryid; productentity.stockfinishes = productmodel.stockfinishes; productentity.guarantee = productmodel.guarantee; productentity.installation = productmodel.installation; rpproduct.insert(productentity); rpproduct.savechanges(); if (productmodel.selectedcolors != null) { foreach (var colorid in productmodel.selectedcolors) { data.models.orm.entity.productentity.color color = rpcolor.firstordefault(x => x.id == colorid); productentity.colors.add(color); } db.savechanges(); } return redirecttoaction("productlist"); } else { viewbag.error = "an error occurred while adding new product"; return view(); } } there no error, product colors not inserted database. can't repository.
how can add product colors repository or without repository?
sorry bad english :(
i prefer manage many many relations myself not entity framework.
in view need table store colors of products columns colorid , productid. there should dbset on dbcontext.
after can save new entity productcolors stores colorid , productid. entities color , product can have reference table, not color , product table.
public class productcolor : base.baseentity { public productcolor() { } public int colorid { get; set; } public virtual color color { get; set; } public int productid { get; set; } public virtual product product { get; set; } }
Comments
Post a Comment