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: ,
16 comments

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!!!!

Create a master details application with WPF and the Entity framework November 26, 2010

Posted by fofo in general .net, Visual Studio 2010, WPF.
Tags: ,
2 comments

I have been studying WPF for some time now and I am impressed with its extensive API and the incredible-stunning applications that one can build.

In this post I would like to show you how to create a WPF application that will fetch data from a database. Then I will enhance the simple application by creating a master details form. I will demonstrate all these with a hands on, step by step example. I will do all that without writing a single line of code.

My favourite data access technology is Entity framework and I am going to use EF to fetch data from the database.

I am going to use the Pubs database. You can download the installation scripts of the Pubs database from here.

I am going to use Visual Studio 2010 and C# as the development language. So here it is.

  1. Fire up Visual Studio 2010. Create a new project and choose “Wpf Application” from the available templates. Save your project with a name that you want in the desired location.
  2. Add new item in your WPF project. From the available items choose “Ado.Net Entity Data Model” name your model pubs.edmx and click Add. In the Entity Data Model wizard click generate from database and click Next. Create a new connection and choose the SQL Server instance that the Pubs database is attached to. Then click OK to close the  Connections window and return to the Entity Data model wizard window. Click Next and choose from the “Choose your Database Objects” window all the tables. Then click Finish.
  3. Go to Data->Show Data Sources option and click Show Data Sources option. You will see immediately all the classes availablee to use in my application. That is awesome. Drag and drop the Publishers class on the MainWindow.xaml file.

Now let’s go and have a look at the XAML code generated. We notice that we have a DataGrid control.Some of the xaml code generated is show in the snippet below.

<Window.Resources>         <CollectionViewSource x:Key=”publishersViewSource” d:DesignSource=”{d:DesignInstance my:publisher, CreateList=True}” />     </Window.Resources>     <Grid DataContext=”{StaticResource publishersViewSource}”>         <DataGrid AutoGenerateColumns=”False” EnableRowVirtualization=”True” Height=”125″ HorizontalAlignment=”Left” ItemsSource=”{Binding}” Margin=”12,12,0,0″ Name=”publishersDataGrid” RowDetailsVisibilityMode=”VisibleWhenSelected” VerticalAlignment=”Top” Width=”479″>             <DataGrid.Columns>                 <DataGridTextColumn x:Name=”pub_idColumn” Binding=”{Binding Path=pub_id}” Header=”pub id” Width=”SizeToHeader” />                 <DataGridTextColumn x:Name=”pub_nameColumn” Binding=”{Binding Path=pub_name}” Header=”pub name” Width=”SizeToHeader” />                 <DataGridTextColumn x:Name=”cityColumn” Binding=”{Binding Path=city}” Header=”city” Width=”SizeToHeader” />                 <DataGridTextColumn x:Name=”stateColumn” Binding=”{Binding Path=state}” Header=”state” Width=”SizeToHeader” />                 <DataGridTextColumn x:Name=”countryColumn” Binding=”{Binding Path=country}” Header=”country” Width=”SizeToHeader” />             </DataGrid.Columns>         </DataGrid>     </Grid>

We notice the CollectionViewSource which is our binding source to the underlying data.Let’s see some of the code that it is generated from Visual Studio for us in the code behind file.

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {

WpfMasterDetailEF.pubsEntities pubsEntities = new WpfMasterDetailEF.pubsEntities();
 // Load data into publishers. You can modify this code as needed.
System.Windows.Data.CollectionViewSource publishersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("publishersViewSource")));
System.Data.Objects.ObjectQuery<WpfMasterDetailEF.publisher> publishersQuery = this.GetpublishersQuery(pubsEntities);
publishersViewSource.Source = publishersQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
 }

4) Run your application and you will see the data in your application.That is pretty cool and I did not have to write a single line of code.

5) Now we will enhance this application by creating a master details application. From the Data->Show Data Sources drag and drop the employees entity to the MainWindow.xaml.

Have a look at the picture below.

6) Have a look at the generated code.

Note the second CollectionViewSource which is our binding source to the undelying data.

 <CollectionViewSource x:Key="publishersemployeesViewSource" Source="{Binding Path=employees, Source={StaticResource publishersViewSource}}" />

7) Run your application and see that we have a master/detail functionality out of the box. That is pretty cool.

Hope it helps.

Follow

Get every new post delivered to your Inbox.

Join 1,788 other followers