Thursday, 21 July 2011

Simply use of EFM and Lambda

Recently I had a request from a client to make enhancements to an existent application. They wanted to add more options to two lists, drop down lists.

One of these lists contain countries where their products were manufactured. In the original list there were around 37 countries. They wanted to add more countries to this list. However there was a catch

The data for the countries drop down list is stored on a table called Countries. 



Now there is the need to add more countries to the list, say 160 more countries.
The only issue is that, the main table, let’s called products already got rows of data pointing to the country id of the Country table.
For example several of the products have a 7 on their MANUFACTARED_ID column meaning these product are manufactured in Denmark. We can’t slide new countries between the existing ones. The current relationship of the product and the countries were they are manufacture would be broken!
What about putting the new countries, 160 right in the end of the table?
In this way the existing countries keep their ID’s and any references to this id, COUNTRY_ID, by any of our database entities remain valid.

This is a potential solution; the only issue with this approach is that all the new countries will come last!
So if Albania and Afghanistan are added they will not come before Australia but they will be placed all the way down the list.

So what we need to do is to modify the code so we retrieve and sort the countries before we populate the drop down list. By the way the existing code didn't sort the countries so We need to change this:

public List RetrieveCountries() {
List countriesList = ubfContext.Countries.ToList();
}
We simply add a lambda expression a pass it to the Entity Framework query:

public List RetrieveCountries() {
var countries = ubfContext.Countries.OrderBy(country => country.COUNTRY_NAME);
return countries.ToList();
}


Even that Albania and Afghanistan , and all the other new countries, were placed after the existent countries in the Country table They are being displayed, in the list, in the right order.

No comments:

Post a Comment