jump to navigation

Create a master-detail Windows Forms application with EF March 15, 2012

Posted by fofo in C#, Visual Studio 2008, Visual Studio 2010.
Tags: ,
trackback

I have been teaching in the past few weeks many people on how to use Entity Framework. I have decided to provide some of the samples I am using in my classes.

In this post I will show you a step by step example on how to build a Windows Forms (Master – Details) application with C# and Entity Framework. Have a look in this post if you would like to see how to implement similar functionality with WPF.

First let’s try to define what EF is and why it is going to help us to create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of Object-relational impedance mismatch. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.

In my other development blog (ASP.Net blog) you can find many posts on Entity Framework.Have a look if you want.

We will need a database and a version of SQL Server.You can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample AdventureWorkLT database, click here

Let’s start with our hands-on example.

1) Launch Visual studio 2010 Express edition or any other edition you may have installed.

2) Create a new class library project and name it AWEFModel. Choose C# as your language of development.Ιn this project I will keep my Entities Data Model in a separate project and then I will consume this project from a separate application (Windows Forms)

3) Remove the Class1.cs file.Right – click on your project from the Solutions Explorer window and Add a new Item. From the available templates choose ADO.NET Entity data model. Give it the name ΑdventureWorksLTEntities.edmx and click the Add button.

4) Then the Wizard pops up. Choose “Generate from Database”. Have a look at the picture below

5) Click Next and Create a New Connection (as you see in the picture below) and hit the Continue button.

6) Then follow the instructions as shown in the picture below.Select the local installation of your SQL Server and the database name and then click OK.


7) After you complete the steps above you will see something like the picture below. You can see the Entity connection string and where these setting will be saved.Hit the Next button.Then click Finish

8) If you notice you will see that there is something called Entity connection string that points to the actual database.It is saved in the App.config file of the

9)  Now the wizard will identify the database objects and let us choose which database objects we want to include in our model.I included all the database objects.Hit the Finish button.Ι will include only some of the tables. Have a look at the picture below

Finally, Visual Studio will add the model to the project and will add the necessary references.

10) Have a look at your entity model as it is visualized in the Entity Model Designer. Have a look at the Entity classes and their relationships/associations.Have a look at the properties of each Entity class. Have also a look at the Navigation Properties of each entity class.Basically the entity framework generates classes for all the entities in the designer. You can have a look at the generated code if you want by opening the class file, which in my case is AdventureWorksLTEntities.Designer.cs.

11) Add a new project to your solution, a Windows Forms Application. Name it WindowsFormsEFMD. Add a reference to the System.Data.Entity  and the Entity Framework Model project (AWEFModel)

12) Copy paste the App.config file from the AWEFModel project to the WindowsFormsEFMD project.

13) We will add a datasource to the Windows Forms application (Data–> Add new Datasource). We will add a datasource for the Customer Entity. In the wizard that pops up (Choose a Data Source Type) select Object and then click Next.In the Select the Data Objects choose from the AEFModel(It is already in the there) the Customer class /entity. Change the Customer Entity from GridView to Details. Drag and drop the Customer Entity from the Data Sources to the Form1 window.

Have a look at the picture below to see what I mean

Drag and drop from the Data Sources (SalesOrdersHeaders) entity to the Form1 form.

Have a look at the picture below.

14) In the Form1_Load event handling routine type,


private void Form1_Load(object sender, EventArgs e)
{
var ctx = new AdventureWorksLTEntities();

var query = ctx.Customers.Where(c=>c.SalesOrderHeaders.Any());

customerBindingSource.DataSource = query.ToList();

}

15) Ι am querying the database to find only customers that have orders. Run your application.

16) I will show you how easy it is to make changes. Please note that all the changes are made to the entities in the memory and then are persisted back to the database.

17) Go to the customerBindingNavigator control in the Form1 design view.Select the “Save” button and enable it (right-click on it).

18) Then in the customerBindingNavigatorSaveItem_Click event handling routine type.


private void customerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{

      ctx.SaveChanges();
    }

I have made a very small change in the code. I have instantiated the context outside of the local scope

public partial class Form1 : Form
{      AdventureWorksLTEntities ctx = new AdventureWorksLTEntities();

public Form1()
{
InitializeComponent();
}

19) The ctx.SaveChanges() method persists the changes to the database.Run your application and make some changes in the Customers Grid. Click the Save button to persist the changes back to the database. Launch SQL Profiler to see what actually happens in the database.

Leave a comment if you need the source code.

Hope it helps!!!!

About these ads

Comments»

1. Dot Net Rules : Create a master-detail Windows Forms application with EF - March 15, 2012

[...] Have a look in this post if you would like to see how to implement similar functionality with WPF. (read more) Share Posted: Πέμπτη, 15 Μαρτίου 2012 7:11 μμ από το μέλος [...]

2. Sharath Babu - March 18, 2012

Hi,

Great post.I would like to have source code of this.Please share.Thanks

Kind regards
Sharath

Sharath Babu - March 18, 2012

could you email me at sharath82@gmail.com

3. husss - May 21, 2012

very helpful

4. Bjarne Riis - June 25, 2012

Could you email me the code?
Regards,
Bjarne

5. Anoop - July 5, 2012

I am sorry. I missed the save part. Please some delete this comment

6. christian louboutin cheap - July 17, 2012

Fantastic stuff, these are the article types that pave the way for budding bloggers. A great starter kit for times of writers block too.Nice resource Kim!

7. ganesh - July 29, 2012

Nice post .. can you send me the source code for the master detail windows forms using entity framework.
Thanks. yesganesh@gmail.com

sale515 - November 24, 2012

dude…you rules….if this stuff work for me..i’m saved…thanks

8. kumar - January 1, 2013

nice article……btw how to add search option for this datagrid view?

9. Rafic Salem - April 23, 2013

Very Useful. can you send me the source code for the master detail windows forms using entity framework.
Thanks.

10. jado - June 18, 2013

Very nice

11. Samir Shah - June 24, 2013

Can you send me the source code for the master detail windows forms using entity framework?

Thanks

12. Arun - July 17, 2013

Send me the source code arun.msys@gmail.com

13. Viktors - February 6, 2014

nice article :) can you send code? Thanks :) viktors@zitc.lv

14. Mohammed Atef - May 31, 2014

Gr8 article. Plz, can u send my the SRC? Thnx mas.hegazy@gmail.com


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

Follow

Get every new post delivered to your Inbox.

Join 1,787 other followers

%d bloggers like this: