【问题标题】:Linq and Entity Framework Update IssueLinq 和实体框架更新问题
【发布时间】:2012-08-19 16:09:38
【问题描述】:

使用以下代码:

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);  
}

我正在尝试更新多对多关系表。每个部门可以有一组产品,每个产品可以有一组部门。尝试更新产品实体时,我将清除所有扇区,以防用户使用上面的 .Clear() 从复选框列表中选择其他可用扇区。然后从复选框列表中读取并更新。我没有更新记录,而是在具有新的自动递增 ID 的产品中获得了一个新的相同行。所以它正在执行插入而不是更新,我从未指定.AddObject()。

我在这里做错了什么?或者我应该如何正确实现?

谢谢。

【问题讨论】:

  • productObj.Sectors.Add(sectorObj);
  • 我正在为现有的 productObj 实体添加一个部门实体。那有什么问题?这样我就可以更新联结表。 + 它没有进行任何“清除”,但它附加了新创建的行。
  • 您删除并创建了一个新对象,而不是更新。
  • 能否请您解释更多并提供一个例子?原始记录没有从数据库中删除。因此,例如,如果我将 Saeed 作为产品并尝试对其进行更新,我仍然会创建 Saeed + 另一个新行。

标签: c# asp.net sql-server linq entity-framework


【解决方案1】:

而不是这个:

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

这样做:

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

如果您不希望代码与 .Find 发生数据库往返,请改用此 LoadStub 方法: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;
        }
 
    }
}

你的代码应该是这样的:

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

示例用法:http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-with_16.html

【讨论】:

  • 您好,感谢您的回答。您能否解释一下第一个 LINQ 查询有什么问题?因为这适用于网站的大部分内容。
  • 您能告诉我您在db.Sectors.Find 中使用的Find 方法在哪个版本的linq 中?还是 linq2EF?
  • Sector sectorObj = db.Sectors.SingleOrDefault(x =&gt; x.sector_id == SectorID); 这实际上得到了我需要的扇区。
  • Micheal,我可以得到合适的 Sector 对象。另一个产品被插入到产品表中的问题。
  • @user1027620 您的 productObj 是否来自具有 live 上下文的对象?实体框架几乎只适用于附加到上下文的对象。如果您的 productObj 是从内存中的对象构造的,那么它将被视为新对象,即使 ID 与数据库中的现有行匹配。在您编辑的 productObj 上执行此操作:productObj = db.Products.Find(productId),然后 EF 现在可以响应您对 productObj 及其集合(例如扇区)的操作
【解决方案2】:

我不认为删除和重新创建是一个好主意。此外,使用 Clear 不会从数据库中删除,只是从内存中删除。这是你必须做的:

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);  
}

【讨论】:

  • 同样的问题,在数据库中创建了一个新产品,而现有产品没有更新。
  • 你从哪里得到productObj?
猜你喜欢
  • 2011-10-21
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
相关资源
最近更新 更多