Mes entités:plusieurs à plusieurs avec insert référentiel Entity Framework
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; }
}
Mon contrôleur:
[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 a new product";
return View();
}
}
Il n'y a pas d'erreur, mais les couleurs de ce produit ne sont pas insérés dans la base de données. Je ne peux pas le faire avec le dépôt.
Comment puis-je ajouter des couleurs de produit avec le référentiel ou sans référentiel?
Désolé pour le mauvais anglais :(