You need to call
samplesDbEntities.SaveChanges();
before the request 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 you don't get the added user back to objectSetResult is because calling the SingleOrDefault method of the IQueryable object leads to a database query (the actual SQL query string is generated according to the "where" condition, etc.)., And since the object is not yet installed in the database, it is not returned. However, the new object is context bound, and EntityState is set to Added. According to MSDN, objects in the added state do not have the original values in the ObjectStateEntry. The state of objects within an object context is controlled by the ObjectStateManager. Therefore, if you want to check if the object is really connected, you can get 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 summarize - regarding your initial question as to whether this is the correct implementation of UnitOfWork, I don't understand why not. It really maintains a list of objects and tracks changes, etc. Etc. However, the problem you are facing is related to the fact that you are retrieving data from the primary provider, and not from the list of objects that are currently connected to the context.
Yakimych
source share