Entity Framework in asp.net applications

by Mikael Henriksson 11. March 2009 22:50

It is a bit tricky sometimes because of the change tracking. If you start getting / setting data in different object contexts you could end up pressing the save button but not actually saving anything because the object context you use to save changes is actually not the same object context that you made the changes in.

There for I created a base class for my repositories that I can use to handle the creation of the object context.

internal abstract class RepositoryBase
{
	internal ModelEntities _context;
	internal bool _contextReused;

	public ModelEntities GetObjectContext()
	{
		if (!_contextReused)
			return new ModelEntities();

		return _context;
	}

	public void ReleaseObjectContextIfNotReused()
	{
		if (!_contextReused)
			ReleaseObjectContext();
	}

	public void ReleaseObjectContext()
	{
		if (_context != null) _context.Dispose();
		_contextReused = false;
	}
}

So what would be the reason for wanting to reuse the context then? Well let’s say I have an overly complicated way of creating a new entity. I might have to make changes here and there and wait with saving the changes until all steps in the overly complicated way of creating a new entity has been performed. If I open up multiple object contexts not only will performance suffer from instantiating multiple contexts but also… the changes I made won’t stick when I call save changes.

public class Repository : RepositoryBase
{
	public Repository()
	{
		_contextReused = false;
	}

	public Repository(ModelEntities context)
	{
		_contextReused = true;
		_context = context;
	}
	
	public void DoSimpleSomething()
	{
		var context = GetObjectContext();
		var query = from s in context.Something
					select s;
		var summin = query.FirstOrDefault();
		summin.Field = "Value";
		
		var factory = new Factory(context);
		factory.DoComplicatedSomething(summin);

		ReleaseObjectContextIfNotReused();
	}
}
public class Factory : RepositoryBase
{
	public Factory()
	{
		_contextReused = false;
	}

	public Factory(ModelEntities context)
	{
		_contextReused = true;
		_context = context;
	}
	
	public void DoComplicatedSomething(Something summin)
	{
		var context = GetObjectContext();
		summin.SomeReference.Load();
		summin.Some.Field = "whatever"
		' advanced calculations or whatever here
		context.AddToSomething(summin);
		context.SaveChanges();
	}
}

Tags:

Entity Framework

blog comments powered by Disqus