Entity Framework – Yet another Step by Step Guide
Monday, March 30th, 2009Here at Coalition Software we’ve been toying with the idea of using the Microsoft Entity Framework for some time now. It wasn’t until we saw the great demonstration by Nick Goossens at DevDays 2009, that we’ve decided to start using it for our projects.
So I’ve decided to do another Step-by-Step guide, to document our journey and learning experience in the Entity Framework world.
Getting Started
The Database
First we need a database, head over to Codeplex, and download the Adventure Works LT database. For this guide, we’ll look at the Customer, SalesOrderHeader, SalesOrderDetail and Product tables.
The Code
Next, create a new Visual Studio Windows Application project called AdventureWorksUI next, add a new project to your solution called AdventureWorksEF.
We now have 2 projects within our solution, AdventureWorksUI is where we’ll create our user interface and AdventureWorksEF, will be where all our Entity Framework objects are stored.
In the AdventureWorksEF project add a new ADO.NET Entity Data Model, called AdventureWorksModel.edmx. Click on Generate from database, create a new connection to the database. Then select the Customer, SalesOrderHeader, SalesOrderDetail and Product tables, as shown below(click for a larger image).
Leave the Model Namespace as AdventureWorksLTModel. Click Finish.
The UI
Next, add a reference to your AdventureWorksEF project from the AdventureWorksUI project. Open Form1.vb in design view, and place a datagrid called DataGridView1 and a button named button1 on the form. Switch to code view and the button’s Click event. Enter the following code, and hit F5.
Dim ctx As new AdventureWorksEF.AdventureWorksLTEntitiesDim result = From c In ctx.Customer _Where c.Title = "Mr." _Order By c.LastNameDataGridView1.DataSource = result
|
NOTE: You will receive the following error: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid. The fastest workaround for this is to copy the App.Config file from your AdventureWorksEF project to your AdventureWorksUI project. Also If the compiler complains add a reference to System.Data.Entity |
If everything goes well, you should see a list of all customer with a title of Mr. If the above code looks completely weird for you, go do some reading on LINQ, you can find some great tutorial videos here.
Saving data
Add another button to the form, and enter the following code to it’s Click event.
ctx.SaveChanges()
You would need to move the
Dim ctx As New AdventureWorksEF.AdventureWorksLTEntities
line to the top of your class in order for this to work.
Now, make some changes in the grid, hit the save button and the changes will be saved to your database! Easy.
In the next few instalments of this guide, we’ll look at data binding and loading child objects. Until next time, keep coding!