为什么2个不同的实体引用同一个对象? [英] Why 2 different entities reference the same object?

查看:80
本文介绍了为什么2个不同的实体引用同一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Linq To Entities 来获得2个对象m1&平方米.
而且我不明白为什么2个不同的对象引用相同的 Template 表.

我怀疑原因是由于MConfigOnPage1,MConfigOnPage2与MConfiguration之间的连接.也许应该以某种方式拆分它?

此处已附加我的ERD和代码.

我将很感谢您解释为什么会发生这种情况?

谢谢

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?

Here is 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?

推荐答案

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.


这篇关于为什么2个不同的实体引用同一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆