简体   繁体   中英

Linq and Entity Framework Update Issue

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:

Sector sectorObj = db.Sectors.SingleOrDefault(x => x.sector_id == SectorID);  

Do this:

Sector sectorObj = db.Sectors.Find(SectorID);  

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.html

public static class Helpers
{
 
    public static Ent LoadStub<Ent>(this DbContext db, object id) where Ent : class
    {
        string primaryKeyName = typeof(Ent).Name + "Id";
        return db.LoadStub<Ent>(primaryKeyName, id);
    }
 
    public static Ent LoadStub<Ent>(this DbContext db, string primaryKeyName, object id) where Ent: class
    {
        var cachedEnt = 
            db.ChangeTracker.Entries().Where(x => ObjectContext.GetObjectType(x.Entity.GetType()) == typeof(Ent)).SingleOrDefault(x =>
            {
                var entType = x.Entity.GetType();
                var value = entType.InvokeMember(primaryKeyName, System.Reflection.BindingFlags.GetProperty, null, x.Entity, new object[] { });
 
                return value.Equals(id);
            });
 
        if (cachedEnt != null)
        {
            return (Ent) cachedEnt.Entity;
        }
        else
        {
            Ent stub = (Ent) Activator.CreateInstance(typeof(Ent));
 
             
            typeof(Ent).InvokeMember(primaryKeyName, System.Reflection.BindingFlags.SetProperty, null, stub, new object[] { id });
 
 
            db.Entry(stub).State = EntityState.Unchanged;
 
            return stub;
        }
 
    }
}

Your code shall be like this:

Sector sectorObj = db.LoadStub<Sector>(SectorID);  

Sample usage: http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-with_16.html

I don't think deleting and recreating is a good idea. Also, using Clear does not delete from database, just from memory. Here is what you have to do:

using (ICMSEntities db = new ICMSEntities())  
{ 
    foreach (ListItem item in cblSectors.Items)
    {
        int SectorID = item.Convert.ToInt32(item.Value);
        if (item.Selected && !productObj.Sectors.Any(s => s.SectorID == SectorID))
        {
            Sector sectorObj = db.Sectors.Single(x => x.sector_id == SectorID);  
            productObj.Sectors.Add(sectorObj);  
        } 
        else if (!item.Selected && productObj.Sectors.Any(s => s.SectorID == SectorID))
        {
            var sector = productObj.Sectors.Single(s => s.SectorID == SectorID);
            productObj.Sectors.Remove(sector);
        }
    }
    db.SaveChanges();  
    Response.Redirect("~/Products.aspx", true);  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM