为什么两个不同的实体引用同一个对象?
我使用 Linq To Entities 来获取 2 个对象 m1 &平方米。 我不明白为什么两个不同的对象引用相同的模板表。
我怀疑是由于MConfigOnPage1、MConfigOnPage2与MConfiguration之间的连接造成的。也许应该以某种方式分割它?
我附上了我的 ERD 和代码。
我将不胜感激解释为什么会发生这种情况?
谢谢
var cxt = new Entities();
//this returns MConfiguration with Id=19
var m1 = (from mop in cxt.MConfigOnPage1
where mop.SiteMapId == 15 && mop.HolderId == 13
select mop.MConfiguration).FirstOrDefault();
//this returns MConfiguration with Id=40
var m2 = (from mop in cxt.MConfigOnPage2
where mop.SiteMapId == 15 && mop.HolderId == 1
select mop.MConfiguration).FirstOrDefault();
var t1 = m1.Holder.Template;
var t1.Code = 13;
var t2 = m2.Holder.Template;
//I expect that **t2.Code** to be 0, but it equals 13
//This behavior tells me that m1 & m2 reference the same Template object,
// BUT shouldn't m1 & m2 to have their own Template objects?
ERD
MConfiguration 表数据
持有者表数据 _______________________________________________________________________ 模板表格数据
_____________________________________
I use Linq To Entities to get 2 objects m1 & m2.
And I don't understand why 2 different objects reference the SAME Template table.
I suspect that the reason due to the connection between MConfigOnPage1, MConfigOnPage2 with MConfiguration. Maybe it should be splitted somehow?
I attached my ERD and the code.
I'll be grateful for explanation why this happens?
Thank you
var cxt = new Entities();
//this returns MConfiguration with Id=19
var m1 = (from mop in cxt.MConfigOnPage1
where mop.SiteMapId == 15 && mop.HolderId == 13
select mop.MConfiguration).FirstOrDefault();
//this returns MConfiguration with Id=40
var m2 = (from mop in cxt.MConfigOnPage2
where mop.SiteMapId == 15 && mop.HolderId == 1
select mop.MConfiguration).FirstOrDefault();
var t1 = m1.Holder.Template;
var t1.Code = 13;
var t2 = m2.Holder.Template;
//I expect that **t2.Code** to be 0, but it equals 13
//This behavior tells me that m1 & m2 reference the same Template object,
// BUT shouldn't m1 & m2 to have their own Template objects?
ERD
MConfiguration table data
Holder table data ____________________________________________________________________________ Template table data
_____________________________________
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
链接到实体可确保在给定上下文中,如果您获取相同的实体(通过数据库中的主键),您将获得相同的对象。
如果您多次从模板表中选择该行,您将看到相同的行为。每当您重新查询任何对象时,您总是会得到相同的实例。
这通过缓存为您提供了性能优势,并防止在同一上下文中对同一对象进行多次编辑导致冲突。
Link to Entities ensures, within a given context, if you fetch the same entity ( by primary key in DB) you will get the same object.
You will see this same behavior is you selected the row from the template table multiple times. You will always get the same instance back whenever you re-query for any object.
This gives you performance advantages through caching and prevents multiple edits to the same object in the same context from causing conflicts.