首先是表结构,一个一对多的关系,和一个单独的表来做测试
1: var db = new TestDBEntities();
2: var obj1 = db.tab1.FirstOrDefault();
3: var list1 = db.tab1.ToList();
4:
5: var user1 = db.Users.FirstOrDefault();
6: var userlist = db.Users.ToList();
7:
8: var order1 = db.Orders.FirstOrDefault();
9: var orderlist = db.Orders.ToList();
10:
11:
12: cache.Put("obj1", obj1);
13: Console.WriteLine("单独表个体");
14: cache.Put("list1", list1);
15: Console.WriteLine("单独表list");
16:
17: cache.Put("user1", user1);
18: Console.WriteLine("user表个体");
19: cache.Put("userlist", userlist);
20: Console.WriteLine("user表list");
21:
22: cache.Put("order1", order1);
23: Console.WriteLine("order表个体");
24: cache.Put("orderlist", orderlist);
25: Console.WriteLine("order表list");
查出来,放入cache,貌似没什么问题
但是如果用下面的写法
1: tab1 obj1;
2: Listlist1;
3: Users user1;
4: Listuserlist;
5: Orders order1;
6: Listorderlist;
7: using (var db = new TestDBEntities())
8: {
9: db.tab1.MergeOption = System.Data.Objects.MergeOption.NoTracking;
10: db.Users.MergeOption = System.Data.Objects.MergeOption.NoTracking;
11: db.Orders.MergeOption = System.Data.Objects.MergeOption.NoTracking;
12: obj1 = db.tab1.FirstOrDefault();
13: list1 = db.tab1.ToList();
14: user1 = db.Users.FirstOrDefault();
15: userlist = db.Users.ToList();
16: order1 = db.Orders.FirstOrDefault();
17: orderlist = db.Orders.ToList();
18: }
19:
20: cache.Put("obj1", obj1);
21: Console.WriteLine("单独表个体");
22: cache.Put("list1", list1);
23: Console.WriteLine("单独表list");
24:
25: cache.Put("user1", user1);
26: Console.WriteLine("user表个体");
27: cache.Put("userlist", userlist);
28: Console.WriteLine("user表list");
29:
30: cache.Put("order1", order1);
31: Console.WriteLine("order表个体");
32: cache.Put("orderlist", orderlist);
33: Console.WriteLine("order表list");
两种写法的区别在于
1、使用了using,关闭数据连接
2、使用了notracking,或者使用
order1 = db.CreateObjectSet().FirstOrDefault();
这种泛型形式
Orders关联的Users是唯一的。此时,会报这个错误。
注意,只有在一对多关系的多方放入缓存时,他要获取一那方的数据时会出错
一方放入,对应多方是集合,不会报错
已找到问题的原因,