Well most of our applications are driven by a relational database and business layer associated with it. The amount of time spent to establish a communication between these two can be substantial. So Microsoft has introduced a framework for easy data abstraction called Entity Framework (AEF). AEF does wonders in support of LINQ to Entity and in this article we will have a detailed demonstration.
The Entity Framework is an abstraction conceptual schema over the logical database schema (Relational database). It allows us to eradicate the O-R mismatch between RDBMS and the application logic which is common in data driven applications. (O-R impedance mismatch; (Details can be found here)).
It was introduced with .Net Framework 3.5 Sp1 and extensively improved in .Net 4.0.
In the following example I am going to use Nortwind Database (SQL CE). Northwind is a Microsoft sample database for customers and order management. (NorthWind Schema , NorthWind Database SQLCE) .
Let's add the Northwind database to our project (Refer My post to add a SQLCE database to VS).
Then add Entity Data Model to the project. Let's name the Entity Model as "NWModel".
On click of Add it will guide us through a wizard and follow the steps by selecting Northwind database.
When click on finish VS will create the Entity for us. Also will add a reference to System.Data.Entity.
To check the Field to property mapping, select Customer entity in data model and on right click we will find Table Mapping . You will find the Scalee Fields of RDBMS to property mapping.
We Also check the App.config file; it will add a line for connection string.
Now to check with the business entities lets select in the solution explorer and click on View the class diagram.So Except NWEntity all other Business Entities are inherited from Entity Object for easier management and coordination among themselves.
Let's go to the code and check how it will work to restive data. NwEntity is a wrapper around the entities and can be used to retrieve data related to entities. Have a look at the NwEntity Class bellow.
So In our current application we need to load all the customers and orders on their respective load click. And we can do that with a very small piece of code as below.
private void btnLoadCustomers_Click(object sender, RoutedEventArgs e)
NWEntity objContext = new NWEntity();
var customers= objContext.Customers.ToList();
lstData.ItemsSource = (from c in customers select c.Company_Name);
private void btnLoadOrders_Click(object sender, RoutedEventArgs e)
var orders = objContext.Orders.ToList();
lstData.ItemsSource = (from o in orders select o.Order_ID);
This is how Entity Framework eases the enterprise application development.
Download the code used for this article SourceCode
C# Corner. All contents are copyright of their authors.