Creating Application using WPF Commanding and ADO.NET Entity Framework – (Part 2) Inserting Data

Posted by: Mahesh Sabnis , on 8/19/2010, in Category WPF
Views: 38338
Abstract: In this article I will explain, how to make use of the public properties bound with XAML elements. Using Binding Mode as TwoWay, the object can be constructed and this object can be send back to the Data access using CommandParameter.
In this article, I will explain how to make use of the public properties bound with XAML elements. Using Binding Mode as TwoWay, the object can be constructed and this object can be send back to the Data access using CommandParameter. For this article, I will be using the ADO.NET EF data access library, which I have created in previous article of Creating Application using Windows Presentation Foundation (WPF) Commanding and ADO.NET Entity Framework – (Part I) Fetching Data
In this article, we will discuss the use of CommandParameters property for passing values from XAML to the data access, using XAML only mechanism.
Step 1: In the WPF project created in the previous article, add a new class file in ‘ViewModel’ folder, name it as ‘NewEmployee_Command_ViewModel.cs’. Write the following code in it.
C#
using System;
using System.Windows.Input;
using DataAccessLibrary;
 
namespace WPF_ADONET_EF_Commanding
{
    public class CreateEmployeeCommand : ICommand
    {
        CreateEmployeeViewModel objCreateEmp;
 
        public CreateEmployeeCommand(CreateEmployeeViewModel createEmp)
        {
            objCreateEmp = createEmp;
        }
        public bool CanExecute(object parameter)
        {
            bool action = false;
 
            if (objCreateEmp.NewEmployee != null)
            {
                action = true;
            }
 
            return action;
        }
        public event EventHandler CanExecuteChanged;
 
        public void Execute(object parameter)
        {
            objCreateEmp.InsertNewEmployee(objCreateEmp.NewEmployee); 
        }
    }
 
 
    public class CreateEmployeeViewModel
    {
        public Employee NewEmployee { get; set; }
 
        DataAccess objDs;
 
        public CreateEmployeeViewModel()
        {
            NewEmployee = new Employee();
            objDs = new DataAccess();
        }
 
        public ICommand CreateNewEmployee
        {
            get
            {
                return new CreateEmployeeCommand(this);
            }
        }
 
        public void InsertNewEmployee(Employee objEmp)
        {
            objDs.CreateEmployee(objEmp); 
        }
    }
}
 
VB.NET (Converted Code)
Imports System
Imports System.Windows.Input
Imports DataAccessLibrary
 
Namespace WPF_ADONET_EF_Commanding
      Public Class CreateEmployeeCommand
            Implements ICommand
            Private objCreateEmp As CreateEmployeeViewModel
 
            Public Sub New(ByVal createEmp As CreateEmployeeViewModel)
                  objCreateEmp = createEmp
            End Sub
            Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
                  Dim action As Boolean = False
 
                  If objCreateEmp.NewEmployee IsNot Nothing Then
                        action = True
                  End If
 
                  Return action
            End Function
            Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
 
            Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
                  objCreateEmp.InsertNewEmployee(objCreateEmp.NewEmployee)
            End Sub
      End Class
 
 
      Public Class CreateEmployeeViewModel
            Public Property NewEmployee() As Employee
 
            Private objDs As DataAccess
 
            Public Sub New()
                  NewEmployee = New Employee()
                  objDs = New DataAccess()
            End Sub
 
            Public ReadOnly Property CreateNewEmployee() As ICommand
                  Get
                        Return New CreateEmployeeCommand(Me)
                  End Get
            End Property
 
            Public Sub InsertNewEmployee(ByVal objEmp As Employee)
                  objDs.CreateEmployee(objEmp)
            End Sub
      End Class
End Namespace
 
Note: In the above code, the namespace is the same as the application name. This helps us to refer the class in the XAML directly, by registering this namespace in the XAML.
The above code shows Command class for managing ‘Create New Employee’ operations from XAML. The ‘CreateEmployeeViewModel’ defines the logic for making call to Insert New Employee using the Data Access Library. 
Step 2: In the Views folder, add a new user control and name it as ‘EmployeeView’. This user control contains the following Xaml:
<UserControl x:Class="WPF_ADONET_EF_Commanding.EmployeeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:viewModel="clr-namespace:WPF_ADONET_EF_Commanding"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="514">
    <UserControl.Resources>
        <viewModel:CreateEmployeeViewModel x:Key="EmpCreateNew"></viewModel:CreateEmployeeViewModel>
    </UserControl.Resources>
    <Grid x:Name="grdMain" DataContext="{Binding Source={StaticResource EmpCreateNew}}">
        <Grid x:Name="grdChild" DataContext="{Binding Path=NewEmployee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="43*" />
            <RowDefinition Height="49*" />
            <RowDefinition Height="47*" />
            <RowDefinition Height="50*" />
            <RowDefinition Height="111*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="238*" />
            <ColumnDefinition Width="276*" />
        </Grid.ColumnDefinitions>
       
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="11,12,0,0" Name="textBlock1" Text="EmpNo" VerticalAlignment="Top" Width="180" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="11,16,0,0" Name="textBlock2" Text="EmpName" VerticalAlignment="Top" Width="180" Grid.Row="1" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,16,0,0" Name="textBlock3" Text="Salary" VerticalAlignment="Top" Width="180" Grid.Row="2" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,14,0,0" Name="textBlock4" Text="DeptNo" VerticalAlignment="Top" Width="180" Grid.Row="3" />
            <TextBox Grid.Column="1" Height="23"
                     HorizontalAlignment="Left" Margin="70,14,0,0"
                     Name="txteno" VerticalAlignment="Top"
                     Width="120"
                     Text="{Binding EmpNo,Mode=TwoWay}"/>
            <TextBox Grid.Column="1" Grid.Row="1"
                     Height="23" HorizontalAlignment="Left"
                     Margin="70,13,0,0" Name="txtename"
                     VerticalAlignment="Top" Width="120"
                      Text="{Binding EmpName,Mode=TwoWay}"/>
            <TextBox Grid.Column="1" Grid.Row="2" Height="23"
                     HorizontalAlignment="Left" Margin="70,16,0,0"
                     Name="txtsalary" VerticalAlignment="Top" Width="120"
                      Text="{Binding Salary,Mode=TwoWay}"/>
            <TextBox Grid.Column="1" Grid.Row="3" Height="23"
                     HorizontalAlignment="Left" Margin="70,14,0,0"
                     Name="txtdno" VerticalAlignment="Top" Width="120"
                      Text="{Binding DeptNo, Mode=TwoWay}"/>
            <Button Content="Create Employee" Grid.Column="1"
                    Grid.Row="4" Height="41" HorizontalAlignment="Left"
                    Margin="62,26,0,0" Name="btnCreateEmployee"
                    VerticalAlignment="Top" Width="144"
                     Command="{Binding Path=DataContext.CreateNewEmployee,ElementName=grdMain}"
                     CommandParameter="{Binding Path=NewEmployee,ElementName=grdChild}"/>
        </Grid>
    </Grid>
</UserControl>
 
 
In the above code, the gray marked code shows that first the namespace is registered in the XAML. The instance of the ‘CreateEmployeeViewModel’ is created in the resources section of the user control. The button defines Command property which is bound with the ‘CreateEmployee’ public property of the ‘CreateEmployeeViewModel’ class. This property returns an object of the ‘CreateEmployeeCommand’ class. This class defines the execution for the insert operation by calling the ‘Execute()’ method.
Grid ‘grdMain’, in the above xaml is bound with an instance of the ‘CreateEmployeeViewModel’ class using the Key defined in the resource dictionary. This initializes all objects in the constructor of the class.
The Grid,’grdChild’ is bound with the ‘NewEmployee’ public property of the ‘CreateEmployeeViewModel’ class. All Textboxes in the ‘grdChild’ grid is bound with the public properties of the Employee class. The bind mode is set to TwoWay, which will create an Employee object.
The CommandParameter property of the Button, is bound with the ‘NewEmployee’ of the ‘grdChild’. This will send the Employee object back to the command class and from this class, it will be passed to ‘InsertNewEmployee()’ method of the ‘CreateEmployeeViewModel’ and finally the object will be delivered to the Data Access Library.
Step 3: Keep the design of MainWindow.xaml similar to the one showed in Task 1 of the previous article. Open the MainWindow.Xaml.cs and write the following code in Loaded event:
C#
EmployeeView objEmpView = new EmployeeView();
grdNewEmp.Children.Add(objEmpView);
 
VB.NET
Dim objEmpView As New EmployeeView()
grdNewEmp.Children.Add(objEmpView)
Step 4: Run the application and insert the Employee record:
Application
Clicking on the ‘Create Employee’ button adds a record in  the database.
Conclusion: The ADO.NET EF and WPF Commanding help to build LOB applications using effective database model based programming and code less development, with commands.   
The entire source code of this article can be downloaded over here
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Vema Reddy on Tuesday, August 7, 2012 4:29 AM
Is it posible with out Entity data model
if possible please tell me

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook