How to set FK properties in many to many relationship?
I have a Business and a Category model.
Each Business has many Categories via an exposed collection (Category is disregarding the Business entity).
Now here is my controller-action:
[HttpPost]
[ValidateAntiForgeryToken]
private ActionResult Save(Business business)
{
foreach (var category in business.Categories)
Context.Categories.Attach(category);
if (business.BusinessId > 0)
Context.Businesses.Attach(business);
else
Context.Businesses.Add(business);
Context.SaveChanges();
return RedirectToAction("Index");
}
Now there are several business.Categories that have their CategoryId set to an existing Category (the Title property of Category is missing tho).
After hitting SaveChanges and reloading the Business from server, the Categories are not there.
So my question is what's the proper way to set Business.Categories with a given array of existing CategoryIds.
When create a new Business however, the following System.Data.OptimisticConcurrencyException exception is thrown when calling SaveChanges:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I have a Business and a Category model.
Each Business has many Categories via an exposed collection (Category is disregarding the Business entity).
Now here is my controller-action:
[HttpPost]
[ValidateAntiForgeryToken]
private ActionResult Save(Business business)
{
foreach (var category in business.Categories)
Context.Categories.Attach(category);
if (business.BusinessId > 0)
Context.Businesses.Attach(business);
else
Context.Businesses.Add(business);
Context.SaveChanges();
return RedirectToAction("Index");
}
Now there are several business.Categories that have their CategoryId set to an existing Category (the Title property of Category is missing tho).
After hitting SaveChanges and reloading the Business from server, the Categories are not there.
So my question is what's the proper way to set Business.Categories with a given array of existing CategoryIds.
When create a new Business however, the following System.Data.OptimisticConcurrencyException exception is thrown when calling SaveChanges:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
No comments:
Post a Comment