开发者

Why 2 different entities reference the same object?

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 &&am开发者_开发技巧p; 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

Why 2 different entities reference the same object?

MConfiguration table data

Why 2 different entities reference the same object?

Holder table data ____________________________________________________________________________ Template table data

Why 2 different entities reference the same object?

_____________________________________

Why 2 different entities reference the same object?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜