jump to navigation

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

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.

ASP.NET 4.0 Entity DataSource and GridView September 27, 2009

Posted by fofo in ASP.NET 4.0, c# 4.0, Visual Studio 2010.
Tags: , , , ,

Recently I had the time to examine thoroughly my blog stats. From that it was evident people liked a lot the posts regarding the new features in .Net 4.0. So in this post I am going to discuss the new Entity DataSource web server control which is  similar to the LINQ to SQL DataSource, except it allows you to use your Entity Framework data object model instead. I will also demonstrates the new features of the GridView control. I have talked about EF and how to build an application with EF and C# in one of my previous posts. In this post I will talk more about the Entity Datasource object and enhancements made in the GridView control.

I will create a sample website as always so it is easier for you to understand.In order to follow along you must have installed in your PC VS 2010 and the .NET 4.0 framework.Obviously we are going to need a data store for our application. I will use the AdventureWorksLt which you can download from this site .

1) Launch Visual Studio 2010 and create a new web site.

2) Choose Asp.Net application from the available templates and C# as the development language

3) You now have your files in the Solution Explorer window.

4) Choose the default.aspx page and go to your Toolbox and under the Data Controls drag and drop an Entity Datasource control on the page.

5) Now you need an Entity Data model that the Entity Datasource can bind to. In the Solution Explorer add (right-click) a new special folder , App_Code

6) Select the App_Code and add a new item(right-click) , ADO.NET Entity Data Model.Leave the default name.

7) In the next window select “Generate from database” and click Necxt.

8) In the next window of the Entity model wizard create a new connection to you database (AdventureWorksLT)or select an existing connection that points to the same db.

9) Save the entity connection settings in the web.config file

10) Click Next on the wizard window. From all the available db objects we want to include in our model only tables and more specifically only the Products table.

11) Select the table and click Finish. So now we have a Product Entity with all the mappings to the database.

12) Select the Entity Datasource control and click the arrow on the right-top corner and select Configure Data Source.

13) Select in the Named Connection option of the wizard and select the AdventureWorkLTEntities and click Next

14) In the EntitySetName select Product and from the available Entity values select ProductID,Name,ListPrice,Size,Weightand and click Finish.

15) Drag and drop on the default.aspx page a Gridview control (control in your Toolbox data controls area).Give it some formatting from the AutoFormat options

16) Set the datasource of the Gridview control to the Entity datasource.

17) Enable Sorting,Paging and Selection for the Gridview control

18) Run your application by hitting F5 from your keyboard. If everything is ok you will be able to see a list of products in your page.

The imporevement in the GridView control is about selecting rows.If you selected an item in GridView(the third one for example) and then browsed through the pages the third item in every page will also be selected. That was not always what we wanted. The GridView control did that based on an index it had and used to find the third item on that page.

We can overcome that by enabling the EnablePersistenSelection property and setting it to True.

Then we need to select the DataKeynames property and set it to ProductID.

19) Now if run our application again and select a product in the first page(6th product), and browse through the pages the product in position 6(index 6) is not selected anymore.Now the selection is made over the underlying primary key and not the index in the view of the GridViewControl

Hope it helps!!!

If you need the source code just email me or just comment on this post.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

Building an ASP.Net application with C# and Entity Framework June 27, 2009

Posted by fofo in asp.net, c# 3.0, Sql Server, Visual Studio 2008.

In this post I will show you a step by step example on how to build an ASP.NET application with C# and Entity Framework. 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.

ADO.NET Entity Framework (EF) is included with .NET Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1

So you must donwload and have this software installed if you want to follow along.

It is not going to be a very difficult example. I will just bring data from a entity model to a gridview control and then give the user a way to filter that data.

There are many new enhancements regarding EF in VS 2010 and .Net .4.0 framework. I will not be talking about that since these enhancements are brand new and I am currently looking into them. I will just mention model-first development. This feature allows you to create your entity data model from scratch and then generate a database from it!!! We will do the opposite in this example.

Obviously for this example we will need a database. I will use the Pubs database. This is a well known database and many people are familiar with its schema.You can download the Pubs database from this link. If you need some help on how to install the database have a look here .

I have installed SQL Server 2008 Standard edition in my PC. SQL Server 2008/2005 Express editions will work just fine.You can download SQL Server 2008 Express edition from this link. I have attached the Pubs database in my local instance of the SQL Server.

Let’s start out project.

1) Launch Visual studio 2008

2) Create a new Project and from the available templates choose “ASP.Net web application”

3) Choose C# as your language of development and save your project in your hard drive with a name e.g “EFWebApplication” and click “OK”.

4) Click on the Solutions Explorer and open the Default.aspx page.

5) From the Toolbox drag and drop on the page , a Gridview control, a Textbox control and Button control. Leave the default names.

6) From the Toolbox drag and drop a EntityDatasource control on the page.

7) Choose the data source of the gridview control to be the EntityDatasource1 object.

8) Now we are ready to create our entity model. Right – click on your project from the Solutions Explorer window and Add a new Item. From the availble templates choose ADO.NET Entity data model. Give it the name Pubs.edmx and click the Add button.

9) In the Entity data model wizard window choose Generate from database and click Next .

10) Click New Connection, choose the Server name and from the databases your Pubs database is attached and then connect to the Pubs database and test your connection and click OK

11) If you notice you will see that there is something called Entity connection string and looks like this

metadata=res://*/Pubs.csdl|res://*/Pubs.ssdl|res://*/Pubs.msl;provider=System.Data.SqlClient;provider connection string=”Data Source=FOFO-PC;Initial Catalog=pubs;Integrated Security=True”

The connection string used by the Entity Framework contains not only the database connection string, but a metadata parameter with pointers to three mapping files separated by a pipe character.These mapping files will be generated when we finish this wizard.

12) Click Next on your wizard window and from the databases objects available choose Tables and more specifically the Titles, Authors and TitleAuthor tables. Leave the Model namespace as pubsModel and click Finish.

13) Our new Pubs.edmx file called is created and all the entities are generated which are basically classes derived from the data model . Have a look at the picture below to see the Entity model in the Designer window. You can zoom in and zoom out using the appropriate buttons.


14) Have a look at the Mapping details of each entity type (Authors, Titles,  TitleAuthor). You can change if you want the property names for a particular entity type. For example you can change au_lname to lastname of the Authors entity type. You can also change the names of the entity types and singularise them in a way so they resemble more like a class name. Change Authors to Author and Titles to Title from the Designer.

15) Go to your default.aspx page and click on the EntityDatasource object and hit the option Configure Data Source. In the window that appears choose Named Connection and select the PubsEntities that will apear in the drop-down and hit the Next button.


16) In the next step from the EntitySetName select authors. Select all fields and and enable automatic inserts,updates,deletes and hit the Finish button.


17) In your gridview control enable paging,sorting,editing,deleting and selection.


18) Build and run your application and see the records in your web page. Try to sort,edit, delete records. Well done!!!!

19) Let’s give the ability to the user to apply a filter to the data by typing something to the textbox and return only the relevant data.Choose your EntityDatasource object and from the Properties window select  Where. Click on the “…” to launch the Expression editor window.

20) We will create an expression to use it as a filter(e.g filter the records by city name). The expression could be something like this

it.city=@city OR @city IS NULL

This expression above is written in Entity SQL which is T-SQL like syntax.

Click the Add Parameter button and under name write “city” and the value will be a control, so from the Parameter Source select Control and from the ControlID your textbox control (e.g TextBox1)

Go to show advanced properties and in the “Type” field choose String.  Your settings should be like this:


21) Hit the OK button to close the Expression Editor window. Hit F5 to run your application. In the textbox type

“Oakland” and hit the button control. See the filtered results. That is all!!!! We did that without writing a single line of code.

If you need the source code for this example, just leave a comment and I will email it to you as soon as possible.

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl