find a location for property in a new city
Showing posts with label patterns practices. Show all posts
Showing posts with label patterns practices. Show all posts

Friday, 18 March 2011

How to update a detached entity in Entity Framework

If you are using Entity Framework and closing or disposing of your DataContexts (read database connections) as soon as your Linq to Entities query have finished, which I believe you should, you will run into the situation where saving changes to an updated entity will be ineffectual.

I've discussed before that I think deliberately keeping database connections open is bad in Entity Framework but when practicing this technique you will find saving changes to an updated entity no longer works as it used to when the DataContext was left open as long as it liked.

This is because when you open a DataContext you are also starting up change tracking. Change tracking will keep a note of if your entity has been changed. This is important when you call SaveChanges on that DataContext because it needs to know if there have been any changes to save.

If, however, you open your DataContext, do you Linq to Entities query to get an entity and then dispose of your DataContext your entity is now detached. To SaveChanges you will need to open an new DataContext, which will have no idea that this entity has been changed. So you need a way to update a detached Entity.

Update a detached entity with your DataContext

You can do this by using the Attach method to attach this entities to the DataContext (so it is now managing it). After you've attached it it will be in the "Unchanged" state so will not do anything on SaveChanges. You can tell it it has been updated by changing its object state to Modified. Then simply save changes.

Here is an example. (This is not my actual code - it is more explicit to aid understanding):

public void UpdateObject(T obj)
{
    using (var context = new MyDataContext())
    {
        context.CreateObjectSet<T>().Attach(obj);
        context.ObjectStateManager.ChangeObjectState(obj, EntityState.Modified);
        context.SaveChanges();
    }
}

Updating a detached model when using EF Code First

Coming back to my blog years later (Feb 2013) to reuse the above code I found it didn't work in Entity Framework Code First Model. This is because the context mentioned above is a different from the DbContext used in Code First and so has different properties and methods. Here is the code I used to make this work in EF Code First:

public void UpdateObject(T obj)
{
    using (var context = new MyDataContext())
    {
        context.Set<T>().Attach(obj);
        context.ChangeTracker.Entries<T>().First(e => e.Entity == obj)
                                              .State = EntityState.Modified;
        context.SaveChanges();
    }
}

Follow britishdev on Twitter

Friday, 4 March 2011

Why you shouldn't use singleton DataContexts in Entity Framework

I have been struggling recently with putting an end to a problem caused my optimistically keeping the same DataContext alive in a singleton pattern. Let me tell you what I found and why I think it is bad.

Getting it wrong will cripple your site

The first and foremost reason why you shouldn't use it is that if you set it up wrong the repercussions are critical. Here's my horror story: after ages of head scratching, wondering why the CPUs are continuously nearing 100% and memory leaks are ubiquitous I finally figured out that DataContexts were not being disposed of. Of course this is by design - lovely singleton pattern...

Anyway, not only were they not being disposed of they were being instantiated with every access of the data. So we ended up with piles of open connections, which I assume were being terminated randomly by some critical process. This causes huge memory utilisation and huge CPU usage trying to reallocate memory.

Fine so it was implemented incorrectly, but it is practically impossible to see that this is happening during development without shelling out for a decent entity framework profiler (like Entity Profiler - it is very much worth it if you don't trust EF).

Data isn't in sync sometimes...

When we were using the singleton well the data often seemed out of sync with the database. It's as if the ObjectContext knew best and didn't really care what the database had to say. This is not wise when you are working on a web farm since your different servers will have a different view of what the data is in its memory.

The way to resolve this is to begin a new connection... In comes the problem of multiplying open and undisposed connections.

Where's the performance gain anyway?

Has anyone any idea of how expensive it is to open a DataContext connection? Answer: "A DataContext is lightweight and is not expensive to create" [citation]. So why is everyone so intent on saving the hassle of creating a DataContext?

You are probably saving a few 10s of milliseconds. The word micro optimisation springs to mind - in which case you probably shouldn't be using Entity Framework.

It allows poor coding

Having a DataContext that is never closed allows you to lazy load whenever you want. You may have left your Service and now be in your Controller or worse still, your View. Accessing the database from a View is asking for performance problems as I'm sure you didn't allow that intentionally. It is most likely because you forgot to eager load all the data you need to populate your view.

This also makes it hard to keep things nice and streamlined since you don't know where all your queries are coming from.

Conclusion

If you are a guru of Entity Framework and you think a Singleton DataContext is for you then by all means go for it. If you aren't convinced you need it and you're just experimenting you could encounter unexpected and serious problems. Don't use singleton because you think it sounds cool!

Also, during fixing up my problems I found the Entity Profiler invaluable. It tracks how many connections have been opened and closed (hopefully they will be equal). It also shows all the actual SQL that is being produced, the results, the query plan and even tips on how to sort your query out. Invaluable!

Follow britishdev on Twitter

Thursday, 14 October 2010

How to set up the Repository pattern using Unity

Recently moved from Spring.NET to Unity 2.0 over here in the London based lovemoney.com. We were already using the Repository pattern and Unit of Work pattern with Entity Framework. Now all there is to do is scrap Spring.NET and bring in Unity. Easy right?

I actually found it very difficult to plagiarise this work off some documentation so I thought I'd help the cause by spilling how I managed it. I'm not going to talk about how to set up the Repository pattern, Unit of Work pattern, or Unity in general. Just how to make a delicious combination of all three.

In my inventory of classes to wire up I have:
  • ContentEntities - this is my ObjectContext
  • UnitOfWork - this is my implementation of IUnitOfWork (Google that for guidance)
  • EntityRepostory<T> - this is my implementation of IRepository<T> where T:class (again for guidance on this pattern Google it)
  • ContentService - This has a dependency property for the ContentRepository of type IRepository<Content>

To wire these all up for the RepositoryPattern to be correctly implemented so that the UnitOfWork is reused correctly I used the following code in my Application_Start() method:
//new container
var container = new UnityContainer();

//set up the unit of works to use the singleton pattern (AKA ContainerControlledLifetimeManager)
container.RegisterType<IUnitOfWork, UnitOfWork>("contentUow", new ContainerControlledLifetimeManager(), new InjectionConstructor(new SocialEntities()));
//get the instance (i have named it to disambiguate in the event of having multiple UOWs (quite likely))
var contentUow = container.Resolve<IUnitOfWork>("contentUow");

//now we have the reference start up a new container
container = new UnityContainer()
//content repository (any other repositories within the model can use this same contentUow instance)
.RegisterType<IRepository<Content>, EntityRepository<Content>>(new InjectionConstructor(contentUow))
.RegisterInstance(typeof(ContentService));

Note I used the ContainerControlledLifetimeManager for the UnitOfWork. There are more for you to choose from, I decided from the description that this is the best for me. Check here for a full list of LifetimeManagers.

This is interesting reading if you are interested in what happens when you ignore the UnitOfWork part of the Repository pattern. Bad things!

Follow britishdev on Twitter

Don't fuck with the repository or unit of work pattern

I am one for not taking patterns as gospel so I have a tendency to use the bits I want and discard the bits I don't. Today I discovered I don't necessarily know best.

At lovemoney.com I have just started using Unity 2.0 to replace Spring.NET as our dependency container. This has meant that I have had to reimplement some of the wiring of the dependencies. This includes our implementation of the Repository pattern for use with Entity Framework.

Now, my problem with the Repository pattern is that I have always struggled to see the point in the UnitOfWork part of the pattern. Just extra typing for me with no/little benefit. I decided that (as with most things I don't understand) they should prove their worth. Reading didn't help their cause so I went for the more drastic way of not using and see what goes wrong. Well, nothing did! So there it is I will never use the Unit of Work pattern again.

Until today that is.

Here is a snippet from my EntityRepository:
public ObjectContext Context { get; private set; }
//in an orthodox implementation this would accept a UnitOfWork instead of an ObjectContext
public EntityRepository(ObjectContext context)
{
    Context = new UnitOfWork(context).Context;
}

And here is the wiring in my Unity configuration:
var container = new UnityContainer();

//content repositories
container.RegisterType<IRepository<LoveContent>, EntityRepository<LoveContent>>(new InjectionConstructor(new ContentEntities()))

Something just wasn't right. I first noticed it when I created a new item and added it to the repository and then tried to delete it. Well deleting the item wasn't the problem, it was the repository knowing what had happened. I deleted the item and it was gone, gone from the database, gone from the data returned from the database but not gone from the Repository when it came to display the results on the page.

So, I figured this was something to do with my bastardisation of the Repository and Unit of Work pattern. I configured Unity correctly to implement this pattern and lo it worked as expected.

So I won!

Well, sort of. I know I thought best, it turned out I didn't, then I came crawling back to convention. But I think I am better off for it. If I had just done what all of the blogs had told me I wouldn't have understood why I was doing it.

Being a curious chap I like to understand everything I use and this has helped me. Hopefully it will help you too if you are scratching your head at the Unit of Work pattern.

But seriously, how do you solve it?

If you are/were struggling with this I have written another blog post that will tell you how to set up the repository pattern with Unit of Work using Unity 2.0.

Follow britishdev on Twitter