Delete Data Using EF in WPF

Introduction

This article show how to delete data using EF in WPF application.

Create wpf application as in figure 1

Output1

Figure 1: Create wpf application

Add ADO.NET entity data model to project as in figure 2 and 3

Output2

Figure 2: Add entity framework

Output3

Figure 3: Wizard

Output4

Figure 4: Configure connection

Output5

Figure 5: Choose version

Output6

Figure 6: Select database objects

MainWindow.xaml

<Window x:Class="DeleteData_WPF_EF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350"
Loaded="Window_Loaded">
<Grid>
<DataGrid x:Name="dgEmployee"
Width="267"
Margin="118,47,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="True"
ColumnWidth="*">
<DataGrid.Columns>
<DataGridTextColumn x:Name="dgrEmpId"
Binding="{Binding EmpId}"
Header="EmpId"
IsReadOnly="True" />
<DataGridTextColumn x:Name="dgrFirstName"
Binding="{Binding FirstName}"
Header="FirstName"
IsReadOnly="True" />
<DataGridTextColumn x:Name="dgrLastName"
Binding="{Binding LastName}"
Header="LastName"
IsReadOnly="True" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="btnDelete"
Click="btnDelete_Click"
Content="Delete" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

MainWindow.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace DeleteData_WPF_EF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
EmployeeDBEntities objEntities = new EmployeeDBEntities();
public MainWindow()
{
InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
dgEmployee.ItemsSource = objEntities.Employees.ToList();
}

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
int empId = (dgEmployee.SelectedItem as Employee).EmpId;
Employee employee = (from r in objEntities.Employees where r.EmpId == empId select r).SingleOrDefault();
objEntities.Employees.Remove(employee);
objEntities.SaveChanges();
dgEmployee.ItemsSource = objEntities.Employees.ToList();
}
}
}

Output of the application as in the following as in figure 7 and 8

Output7

Figure 7: Output of the application before delete

Output8

Figure 8: Output of the application after delete

Summary

In this article we saw how to delete data using EF in WPF application.