Monday, December 3, 2012

DbSet.Find() in Entity Framework

DbSet.Find method in Entity framework provides some cool and awesome features.
Unlike other it doesn’t except lambda expression whereas it accept only primary key(s) value.

var cat = dbContext.Categories.Find(1);

Above will retrieve the category where category id is 1. “categoryid” is defined as primary key in the underlying table. Incase composite primary key we should pass values in the same sequence of keys.

var data = dbContext.Products.Find(1, 10);

So far, behavior is simple but nothing special. Wait ….following features will make it incredible.

Find() will always not make a database trip to fetch the data rather it supports following principles.

     1.  Find the data in memory and returns it.

cat = dbContext.Categories.Find(1);
cat.Description = "Modified";
//Modified data in the memory will be returned
cat = dbContext.Categories.Find(1);

     2.  Look at the newly added data in memory.

var cats = new Category
  CategoryID = 1001, CategoryName = "New Category",
  Description = "New Category Description"
// newly added data in the memory will be returned
cats = dbContext.Categories.Find(1001);

3   3.  It makes a database trip only when 1 and 2 fails to return any data.

Wonderful isn’t it. I really liked it very much.

1 comment:

  1. This is really helpful.Please write some more on entity framework.