Reputation: 1687
I am using EF5 codefirst in an ASP.NET MVC4 app. I have products and partners, and a number of partners can be assigned to a product.
In the Product entity I have this: public ICollection Partners { get; set; }
And in the Partner entity I have this: public ICollection Product { get; set; }
And thus in my sql server a PartnerProducts many-2-many table is created by code first.
I then have this action method:
public ActionResult AssignPartner(long productId, long partnerId) {
var product = productRepository.Find(productId);
var partner = partnerRepository.Find(partnerId);
if (product.Partners == null) {
product.Partners = new List<Partner>();
}
product.Partners.Add(partner);
productRepository.Save();
return RedirectToAction("Edit", new{ Id = productId });
}
But the result is that both a new PartnerProducts row is created (ok) and also a new partner is created in the Partners table ? Somehow EF must think that the partner I add is a new record?
What am I missing here?
Upvotes: 1
Views: 137
Reputation: 102458
Try this:
public ActionResult AssignPartner(long productId, long partnerId)
{
var product = productRepository.Find(productId);
var partner = partnerRepository.Find(partnerId);
// Using Attach - partner will be in state Unchanged in the context
dbContext.Partners.Attach(partner);
if (product.Partners == null)
{
product.Partners = new List<Partner>();
}
product.Partners.Add(partner);
productRepository.Save();
return RedirectToAction("Edit", new{ Id = productId });
}
Upvotes: 1