EF4 – Customizing the OjectContext for LazyLoading!

by Mikael Henriksson 29. May 2009 02:56

In previous post I wrote a minor struggle about POCO. I was reading like a few 100 blog posts about EF4 and came across an interesting post about lazy loading by Julie Lerman. I agree with Rob that lazy loading should be possible to set for a specific collection and I am sure this will be possible in the future but for now we will have to do without I think. My take on it is to allow this to be set in the constructor of the CustomContext. I’ll use an enum for this for now:

public enum Options
{
	None = 0,
	LazyLoading = 1,
	ProxyCreation = 2,
	All = LazyLoading | ProxyCreation
}
Now I can set this straight away. Since I hate code duplication I created a couple of private methods so I don’t have to make mistakes while ctrl+c + ctrl+v.

public class EntityContext : System.Data.Objects.ObjectContext
{
	public ObjectSet<User> Users { get; set; }
	public ObjectSet<Blog> Blogs { get; set; }
	public ObjectSet<Post> Posts { get; set; }

	public EntityContext()
		: base("name=Entities", "Entities")
	{
		CreateObjectSets();	
	}

	public EntityContext(Options options)
		: base("name=Entities", "Entities")
	{
		CreateObjectSets();
		SetContextOptions(options);	
	}

	private void SetContextOptions(Options options)
	{
		switch (options)
		{
			case Options.All:
				this.ContextOptions.DeferredLoadingEnabled = true;
				this.ContextOptions.ProxyCreationEnabled = true;
				break;
			case Options.LazyLoading:
				this.ContextOptions.DeferredLoadingEnabled = true;
				break;
			case Options.ProxyCreation:
				this.ContextOptions.ProxyCreationEnabled = true;
				break;
			case Options.None:
				this.ContextOptions.DeferredLoadingEnabled = false;
				this.ContextOptions.ProxyCreationEnabled = false;
				break;
			default:
				break;
		}			
	}

	private void CreateObjectSets()
	{
		this.Users = CreateObjectSet<User>();
		this.Blogs = CreateObjectSet<Blog>();
		this.Posts = CreateObjectSet<Post>();
	}
}

Now I can go ahead and create my EntityContext with providing the desired options in the constructor:

var context = new EntityContext(Options.LazyLoading);

If it is performance we are after then another option would be what Alex suggests in this specific post of his series of tips regarding EF4.

Tags:

Entity Framework

blog comments powered by Disqus

About the author

Life architect specialized in programming

Month List

Widget Twitter not found.

Root element is missing.X