Wednesday, October 27, 2010

FK Associations vs Independent Association

The main difference between these two is that in Independent Association, there is a strongly typed navigation property layered over the association, while in “FK Association” there is foreign key property on resides in the entity to associate other entity.

Initially Entity Framework supports only Independent Association, but later on it have included “FK Association”. Before Entity Framework team have introduced “FK Association”, the Independent association was called as “First class association”

The main drawback of Independent Association is that, when you have to pass a foreign entity to the target entity, then you will have to select the Foreign entity first. Which again turned in to query to the database if the entity doesn’t exists in the context. Lets see which with our Northwind example.

image

As you can see Category have many products. Now suppose if you want to add new Product with a related Category, then you must have to write something like:

using (NorthwindEntities db = new NorthwindEntities())
{
db.Products.AddObject(new Product()
{
ProductName = "Coke",
UnitPrice = 10,
Category = db.Categories.SingleOrDefault(c => c.CategoryName == "Bevrages")
});
db.SaveChanges();
}



Now if you run the profiler then you can find that the execution of above code results executing two different sql queries to the target database. The first statement is to create the product, and second statement is to relate the product with the specified category.



Later on Entity Framework have introduced “FK Association”, which contains the Foreign key property in the entity set. This is very useful in DataBinding, Dynamic Data, Concurrency Control,  ASP.NET MVC Binders, N-Tier etc.



Using the “FK Association” the same code can be written like:


using (NorthwindEntities db = new NorthwindEntities())
{
db.Products.AddObject(new Product()
{
ProductName = "Coke",
UnitPrice = 10,
CategoryID = 1
});
db.SaveChanges();
}



As you can see that the CategoryID property is  the “FK Association” property which points to the target entity. We don’t have to write select query for this anymore.



Note: This doesn’t mean that you can not write queries like the first on if you use “FK Association”, you still can write the same code in case of “FK Association” as well. Smile



How to create “FK Association”



 



To create “FK association” first create the two entities, lest say we have Product and Category entity. Then from the Toolbox, select the association and create it between the two entities. After that right click on the Association, select property and then edit the reference association. This will bring the below dialog box

image


Just pass on the property which you want to specify for foreign key property.

No comments:

Post a Comment