随笔 - 432  文章 - 0  评论 - 15  阅读 - 63万

ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象

在使用EF更新数据的时候,报如下错:
ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。

原因是:在EF上上下文中不允许存在2个具有相同键的实体。如下(关注下划线的的代码就Ok了):

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public static object BacthSave<T>(string insertedRows, string updatedRows, string deletedRows) where T : class
{
    try
    {
 
        //添加
        if (!string.IsNullOrEmpty(insertedRows))
        {
            List<T> insertedList = JsonHelper.DeserializeData<List<T>>(insertedRows);
            foreach (var model in insertedList)
            {
                //db.Sys_Navigations.Add(btn);
                db.Entry(model).State = EntityState.Added;
            }
            //db.Sys_Buttons.Add(unicorn);//添加到上下文中
            //插入到数据库中
        }
 
        //修改
        if (!string.IsNullOrEmpty(updatedRows))
        {
            Type type = typeof(T);
            List<T> updatedList = JsonHelper.DeserializeData<List<T>>(updatedRows);
            PropertyInfo propertyInfo = type.GetProperty("Id");
 
            foreach (var model in updatedList)
            {
                //注意以下的提示内容,属性名,属性的类型          //string n = propertyInfo.Name;
                //n = propertyInfo.PropertyType.Name;
                //n = propertyInfo.PropertyType.FullName;
                Nullable<int> id = propertyInfo.GetValue(model) as Nullable<int>;
                //string id = model.GetType().InvokeMember("Id", System.Reflection.BindingFlags.GetProperty, null, model, null) as string;//这个方法没测试通过,不知道为啥,求留言
 
                var entry = db.Entry(model);
                if (entry.State == EntityState.Detached)
                {
                    var set = db.Set<T>();
                    T attachedProduct = set.Local.SingleOrDefault(p => propertyInfo.GetValue(p) as int? == id);
                                                         
                    //如果已经被上下文追踪
                    if (attachedProduct != null)
                    {
                        var attachedEntry = db.Entry(attachedProduct);
                        attachedEntry.CurrentValues.SetValues(model);
                    }
                    else //如果不在当前上下文追踪
                    {
                        entry.State = EntityState.Modified;
                    }
                }
                //db.Entry(model).State = EntityState.Modified;
            }
 
        }
 
        //删除
        if (!string.IsNullOrEmpty(deletedRows))
        {
            List<T> deletedList = JsonHelper.DeserializeData<List<T>>(deletedRows);
            foreach (var model in deletedList)
            {
                db.Entry(model).State = EntityState.Deleted;
                //db.Sys_Buttons.Remove(btn);//也可以使用这个方法
            }
        }
        db.SaveChanges();//这里提供保存到数据库中
        return new { success = true, Message = "保存成功!" };
    }
    catch (Exception ex)
    {
        return new { success = false, Message = "保存失败!" };
    }
}

  

posted on   狼来了  阅读(984)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示