tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Useful Find method on DbSet

26 Jul 2010 Entity Framework

The ObjectStateManager contains a lot of information about entities currently in context. In fact it contains complete entities too. So you can try to look into it before issuing query and use it as local cache. For some simple cases, like PK match, you can create extension method in no time.

But in current feature pack for Entity Framework 4 if you’re using new DbSet object you can find Find method, which does exactly this.

You provide PK value (or values if it’s composite) and it’ll first look for that object locally and if not found it’ll try to fetch it from database.

using (testEntities ent = new testEntities())
{
	var data = ent.Masters.Select(x => x.ID).Take(1).First();
	var item1 = ent.Masters.FirstOrDefault(x => x.ID == data);
	// Find method will find it locally, no querying will be done
	var item2 = ent.Masters.Find(data);
}
using (testEntities ent = new testEntities())
{
	var data = ent.Masters.Select(x => x.ID).Take(1).First();
	//var item1 = ent.Masters.FirstOrDefault(x => x.ID == data);
	// here the Find method will not find it and will query database
	var item2 = ent.Masters.Find(data);
}

It’s nothing from what you’ll be excited couple of hours, but every little counts.