Using the following code:
using (ICMSEntities db = new ICMSEntities())
{
productObj.Sectors.Clear();
int[] selected_sectors = cblSectors.Items.Cast<ListItem>()
.Where(n => n.Selected).Select(n => Convert.ToInt32(n.Value)).ToArray();
for (int i = 0; i < selected_sectors.Length; i++)
{
int SectorID = selected_sectors[i];
Sector sectorObj = db.Sectors.SingleOrDefault(x => x.sector_id == SectorID);
productObj.Sectors.Add(sectorObj);
}
db.SaveChanges();
Response.Redirect("~/Products.aspx", true);
}
I am trying to update the many to many relationship tables. Each sector can have a set of products and each product can have a set of sectors. When trying to update a product entity, I am clearing all sectors in case the user chose other available sectors from the checkboxlist using .Clear() above. And then reading from the checkboxlist and updating. Instead of updating the records, I am getting a new identical row in products with the new auto incremented ID. So it’s doing an insert instead of an update and i never specified .AddObject().
What am i doing wrong here? Or how should I implement this correctly?
Thanks.
Instead of this:
Do this:
If you don’t want your code to incur database roundtrip with
.Find, use this LoadStub method instead: http://www.ienablemuch.com/2011/08/entity-frameworks-nhibernate_02.htmlYour code shall be like this:
Sample usage: http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-with_16.html