Posted by: bibhaspaul | 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.

  • Find the data in memory and returns it.

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

  • Look at the newly added data in memory.

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

  • It makes a database trip only when 1 & 2 fails to return any data.

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: