开发者

Is Entity Framework ObjectContext correct implementation of Unit Of Work Pattern?

开发者 https://www.devze.com 2023-01-05 05:13 出处:网络
Entity Framework 4 - STE - simple DB with single table Blogs having BlogID PK column... var samplesDbEntities = new SamplesDBEntities();

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

var samplesDbEntities = new SamplesDBEntities();
var blogId = Guid.NewGuid();
samplesDbEnt开发者_开发知识库ities.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)


You need to call

samplesDbEntities.SaveChanges();

before requerying for the object.

var samplesDbEntities = new SamplesDBEntities(); 
var blogId = Guid.NewGuid(); 
samplesDbEntities.Blogs.AddObject(new Blog() { BlogID = blogId }); 

samplesDbEntities.SaveChanges();

var objectSetResult = samplesDbEntities.Blogs 
                                   .Where(p => p.BlogID == blogId) 
                                   .SingleOrDefault(); 

Update

The reason why you are not getting the added user back in objectSetResult is that calling the SingleOrDefault method of an IQueryable object results in a database query (an actual SQL query string is generated accoding to the "where" condition, etc.), and since the object is not (yet) in the database, it doesn't get returned. The new object is, however, attached to the context, and it's EntityState is set to "Added". According to MSDN, objects in the Added state do not have original values in the ObjectStateEntry. The state of objects inside an object context is managed by the ObjectStateManager. So if you want to check that the object has really been attached, you can fetch it by calling GetObjectStateEntry:

var samplesDbEntities = new SamplesDBEntities();
Blog blog = new Blog() { BlogID = Guid.NewGuid() };
samplesDbEntities.Blogs.AddObject("Blogs", blog);

Blog addedBlog = (Blog)context.ObjectStateManager.GetObjectStateEntry(blog).Entity;

Also note that the EntityState of the retrieved object is "Added".

To sum up - regarding your initial question about whether it is a correct implementation of UnitOfWork, I don't see why not. It does indeed maintain a list of objects and tracks the changes, etc, etc. The issue you encountered, however, is related to the fact that the you are fetching data from the underlying provider, rather from the list of objects currently attached to the context.


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.


Thanks for clarifying your point. I am adding this as another answer since there is quite a bit to say on the matter.

AFAIK, there is no strict universal definition of UoW, so the topic is up for debate of course. My points are the following:

  1. You are adding an entity to the context, but trying to fetch it from the db. Concluding that ObjectContext is not a correct implementation of UoW is not logical.

  2. If you are adding entities to the context in order to later get them out for some reason before persisting changes to the db, you aren't using EF as it is meant to be used. Generally you shouldn't use ObjectStateManager to do that, but you can:

    Blog addedBlog = context.
             ObjectStateManager.
             GetObjectStateEntries(EntityState.Added).
             Where(ent => (ent.Entity is Blog) && ((Blog)ent.Entity).BlogID == blogID).
             Select(ent => ent.Entity as Blog).
             SingleOrDefault();
    
  3. A unit of work is a context object that maintains lists of business entities, tracks the changes to their state during one business transaction. Does EF ObjectContext do that? Yes. Does it provide a reasonable syntax to retrieve an object that is in state "Added"? No, but that's not a requirement for a "correct" UoW implementation anyways. Don't forget - EF is an ORM, and the goal is to track changes to your db in code, and not changes between different parts of your code (that's what you have your business logic for).

And regarding: "what is the point of UoW if I have to persist every entity on its own and not in batch" - the point is that you can add a bunch of objects to the context, and then persist them all in one go by calling SaveChanges. As I already mentioned, the context isn't meant to be used for "carrying" your business objects around. You can, however, retrieve them from ObjectStateManager without persisting changes to the DB if you want to.

0

精彩评论

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