articles

Home / DeveloperSection / Articles / ADO.NET Entity Data Model in WPF

ADO.NET Entity Data Model in WPF

Sachindra Singh18998 06-Aug-2011

The ADO.NET Entity Framework enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. This article will show you how to fetch and show data in datagrid from database using ADO.NET Entity Data Model in WPF. In this article, I will demonstrate the creation of a simple administration program for the "Emp" table from database. The purpose of this small WPF program is to visualize all data of Emp table, and let the user add/delete or modify Emp objects via datagrid.

Code.XAML
<Window x:Class="Example_Of_Data_Entity_Model.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="640" Width="1024" WindowState="Maximized" Loaded="Window_Loaded" WindowStyle="ThreeDBorderWindow" xmlns:my="clr-namespace:Example_Of_Data_Entity_Model">
    <Window.Resources>
        <Style TargetType="{x:Type TabControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabControl}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <TabPanel Grid.Row="0" IsItemsHost="True" Background="Transparent" />
                            <Border Name="ContentPanel" Grid.Row="1" Background="White" BorderBrush="Green" CornerRadius="0,6,6,6" BorderThickness="4">
                                <Border.RenderTransform>
                                    <ScaleTransform x:Name="TabItemScale" ScaleX="1" ScaleY="1" />
                                </Border.RenderTransform>
                                <ContentPresenter ContentSource="SelectedContent" />
                            </Border>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <EventTrigger RoutedEvent="TabControl.Loaded">
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="TabItemScale" Storyboard.TargetProperty="(ScaleTransform.ScaleY)" To="0.0" BeginTime="0:0:0" Duration="0:0:0" AutoReverse="False"/>
                                        <DoubleAnimation Storyboard.TargetName="TabItemScale" Storyboard.TargetProperty="(ScaleTransform.ScaleY)" To="1.0" BeginTime="0:0:0.2" Duration="0:0:1" AutoReverse="False"/>
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabItem}">
                        <Grid>
                            <Border Name="tabBorder" Background="Red" BorderBrush="Red" BorderThickness="2,2,2,0" CornerRadius="6,6,0,0" Padding="9,4,9,3" >
                                <TextBlock Name="tabForeground" Foreground="LightGray" VerticalAlignment="Center" HorizontalAlignment="Center">
                                    <ContentPresenter ContentSource="Header" />
                                </TextBlock>
                            </Border>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter TargetName="tabBorder" Property="Background" Value="Yellow" />
                                <Setter TargetName="tabForeground" Property="Foreground" Value="Blue" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
 
    </Window.Resources>
    <StackPanel>
        <StackPanel>
            <Grid Height="607">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
 
                <TabControl Padding="0" Margin="281,64,0,0" FontWeight="Bold" Height="500" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.RowSpan="2">
                    <TabItem Header="Example  Of Data Entity Model" Name="tabItem1" FontWeight="Normal">
                        <DataGrid AutoGenerateColumns="True" Height="491" Name="dataGrid1" Width="657" HorizontalAlignment="Left" VerticalAlignment="Stretch" Grid.Column="0" EnableRowVirtualization="True" CanUserResizeRows="True" EnableColumnVirtualization="True" AlternatingRowBackground="#FFDDB81D" RowBackground="#FFF4F7EF">
 
                        </DataGrid>
 
                    </TabItem>
                </TabControl>
                <my:Banner Height="50" HorizontalAlignment="Left" x:Name="userControl11" VerticalAlignment="Top" Width="1193" />
                <my:SaveButton HorizontalAlignment="Left" Margin="13,5,0,0" x:Name="userControl21" VerticalAlignment="Top" />
                <my:DeleteButton HorizontalAlignment="Left" Margin="101,5,0,0" x:Name="userControl31" VerticalAlignment="Top" />
 
            </Grid>
 
        </StackPanel>
 
    </StackPanel>
</Window>

 

Code.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
//// adding three namespaces to access ado.net data entity model in application namespaces given below:
using System.Collections.ObjectModel;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
 
namespace Example_Of_Data_Entity_Model
{
    publicpartialclassMainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        NiitEntities ne;//creating class variable of NiitEntities
        //NiitEntities is name of connection string you can see connection string in App.Config file this file implicitly add with ado.net data entity model when you add in application
      
        privatevoid Window_Loaded(object sender, RoutedEventArgs e)
        {
            ne = newNiitEntities();//creating instance of NiitEntities and storing in variable
            dataGrid1.ItemsSource = ne.Emps;//object of NiitEntities accessing table Emps and filling in datagrid that properties is ItemsSource
            dataGrid1.Columns[dataGrid1.Columns.Count() - 2].Visibility = Visibility.Hidden;//hiding column
            dataGrid1.Columns[dataGrid1.Columns.Count() - 1].Visibility = Visibility.Hidden;//hiding column
            userControl21.button1.Click += newRoutedEventHandler(button1_Click);//creating click event of userControl button
            userControl31.button1.Click += newRoutedEventHandler(button2_Click);
        }
        void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult dr = MessageBox.Show("Are you sure want to save data ?", "Save", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (MessageBoxResult.Yes == dr)
            {
                ne.SaveChanges();//SaveChanges is a method of NiitEntities this method call when data is modified
                MessageBox.Show("Data saved successfully");
            }
        }
        void button2_Click(object sender, RoutedEventArgs e)
        {
            Emp t = dataGrid1.SelectedItem asEmp;// t varaiable storing selected item reference of datagrid in Emp type variable
            if (t == null)
            {
                MessageBox.Show("Please select any data");
            }
            else
            {
                MessageBoxResult dr = MessageBox.Show("Are you sure want to delete ?", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (MessageBoxResult.Yes == dr)
                {
                    ne.DeleteObject(t);//DeleteObject is a method of NiitEntities that is parameterized that take object an object that specifies the Entity to delete
                    ne.SaveChanges();
                    MessageBox.Show("Data Deleted Successfully");
                }
 
            }
        }      
        
    }
}
 
Screenshot

Click

ADO.NET Entity Data Model in WPF

 

After selected ADO.NET Data Entity Model select Generate from database from Model Contents then click on next button as shown below:

ADO.NET Entity Data Model in WPF

 

Select New Connection from Entity Data Model Wizard then click on next button as shown below:

ADO.NET Entity Data Model in WPF

 

In Connection Properties wizard provide server name and select database as shown below:

ADO.NET Entity Data Model in WPF

 

Select table from Entity Data Model Wizard (Emp) then click on finish button as shown below:

ADO.NET Entity Data Model in WPF

 

After finished works of Entity Data Model Wizard go on Solution Explorer you will see Model1.edmx file has added when you will click on that file you will see structure of Emp table as shown below:

 

ADO.NET Entity Data Model in WPFADO.NET Entity Data Model in WPF

 

In Solution Explorer you will see another one more file has added with Model1.edmx and file name is App.Config that contains connection string of ADO.NET Data Entity Model as shown below:

App.Config
<?xmlversion="1.0"encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <addname="NiitEntities"connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=ROHIT-PC\SQLEXPRESS;Initial Catalog=Niit;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

 

In below screenshot you will see some data of Emp table in datagrid as shown below:

ADO.NET Entity Data Model in WPF

In below screenshot I am inserting a new record in datagrid then clicked on Save Data button you will see record will be saved in database as shown below:

ADO.NET Entity Data Model in WPF

In below screenshot I am deleting one record from datagrid then clicked on Delete Data button as shown below:

ADO.NET Entity Data Model in WPF

ADO.NET Entity Data Model in WPF



Updated 07-Sep-2019

Leave Comment

Comments

Liked By