实体框架ObjectContext是否正确执行工作单元? [英] Is Entity Framework ObjectContext correct implementation of Unit Of Work Pattern?

查看:116
本文介绍了实体框架ObjectContext是否正确执行工作单元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体框架4 - STE - 具有单表的简单DB具有BlogID PK列的博客

  var samplesDbEntities = new SamplesDBEntities(); 
var blogId = Guid.NewGuid();
samplesDbEntities.Blogs.AddObject(new Blog(){BlogID = blogId});
var objectSetResult = samplesDbEntities.Blogs
.Where(p => p.BlogID == blogId)
.SingleOrDefault();

(执行结果=> objectSetResult ==最后一行后为空) )



AFAIK,ObjectContext是UoW模式的实现,在这种情况下,我想我应该从ObjectSet(Repository) 标记为短暂
有人可以解释一下我做错了什么,为什么objectSetResult在这里有空值?



(是的,我知道ObjectStateManager,但对我来说,更多是上述架构问题的补丁)

解决方案

在示例中违反的模式不是单位工作模式,而是身份映射。



工作单位轨迹通过代码对对象进行的更改而不是您手动进行的更改。



身份映射模式使对象上下文具有用于单键值的单个实体实例。对于我来说,这是奇怪的,但实体框架(以及LINQ 2 SQL)不会在每种情况下映射对象标识,上述情况就是这种情况之一。


Entity Framework 4 - STE - simple DB with single table Blogs having BlogID PK column...

var samplesDbEntities = new SamplesDBEntities();
var blogId = Guid.NewGuid();
samplesDbEntities.Blogs.AddObject(new Blog() { BlogID = blogId });
var objectSetResult = samplesDbEntities.Blogs
                                       .Where(p => p.BlogID == blogId)
                                       .SingleOrDefault();

(result of code execution => objectSetResult == null after the last line)

AFAIK, ObjectContext is implementation of UoW pattern and in which case I guess I should get the result back from ObjectSet (Repository) just "marked as transient" Can someone explain me what I am doing wrong and why objectSetResult has null value here?

(Yes, I am aware of ObjectStateManager, but to me it is more of a patch for the upper mentioned architectural problem)

解决方案

The pattern violated in your example is not Unit Of Work pattern but Identity Mapping.

Unit of Work track changes made to objects by your code instead of you take care about that manually.

Identity Mapping pattern enacts object context to have single entity instance for single value of primary key.

It is strange for me but Entity Framework (as well as LINQ 2 SQL) does not map object identity in every situation, and situation described above is one of such cases.

这篇关于实体框架ObjectContext是否正确执行工作单元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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