This tutorial will teach you WPF Entity framework Core implement crud operations step by step. whose who interested in .Net Core Entity framework this is the best place which you learn.
First create a new project
Create new project on textbox type blank select blank solution give the name of the project I given name as StudentCrudApplication
After given the name Click create button.
Black Solution has been created with name of StudentCrudApplication
We should create following Class Libraries
1. Crud.Domain – class library
2. Crud.EF – class library
3.Crud.UI – wpf application
Crud.Domain
After that right click the Solution
Add a new project select WPF Class library
Give the name as Crud.Domain
Click Create.then your Crud.domain has been created.
After that right click the Solution
Add a new project select WPF Class library
After that create another class library as Crud.EF as we did ealiar.
Give the name as Crud.EF
After that right click the Solution
Add a new project select WPF Application
Give the name as Crud.UI
Click Next and Create then
Now you will be able to see structure of the solution
- Crud.Domain
- Crud.EF
- Crud.UI
you can see the screen shot image below
After that select the Crud.EF and right click install the Manage NuGet Packages
ADD the Following DEPENDINIES
- Microsoft.EntityframeworkCore.Sqlserver
- Micosoft.EntityFrameworkCore.Design
- Microsoft.EntityframeworkCore.Tools
Install all Dependencies
Type name of the Dependencies and install them.
Click Install
After complete the installation
Crud.Domain
Select the Crud.domain
Create the folder
Right click the crud.domain add-New folder and name it as Model
Inside the model folder create class file which name is
Student.cs
and paste the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | using System; using System.Collections.Generic; using System.Text; namespace Crud.domain.Model { public class Student { public int id { get; set; } public string stname { get; set; } public string course { get; set; } } } |
Create the Student . inside the class consist of following properties id,stname,course
After that Create the folder inside the Crud.Domain which name is Services
inside the folder have to create the interface which name is IDataService
the purpose of creating the file do the crud operations and called as entity all table are entity crud operation.
IDataService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Crud.domain.Services { public interface IDataService<T> // called as entity all table are entity #crud optation { Task<IEnumerable<T>> GetAll(); Task<T> Get(int id); Task<T> Create(T entity); Task<bool> Delete(T entity); Task<T> Update(T entity); } } |
modelBuilder.Entity<Student>().HasKey(e => e.id); // set as the primary key here
database connection i will create the separte class and inhert the StudentDBContext class.
StudentDBContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using Crud.domain.Model; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace Crud.EF { public class StudentDBContext : DbContext { public DbSet<Student> Student { get; set; } public StudentDBContext() { } public StudentDBContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Student>().HasKey(e => e.id); } } } |
CrudContextFactory.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using System; using System.Collections.Generic; using System.Text; namespace Crud.EF { public class StudentContextFactory : IDesignTimeDbContextFactory<StudentDBContext> { public StudentDBContext CreateDbContext(string[] args = null) { var options = new DbContextOptionsBuilder<StudentDBContext>(); options.UseSqlServer("Server=.; Database=studentcrud; Trusted_Connection=True"); return new StudentDBContext(options.Options); } } } |
select Crud.Ef right click set as a started project then go to the main menu
Tools -> NuGet Package Manager -> Package Manager Console
then you can get the console . you have add-migration initial
1 | PM>add-migration initial |
then migration files has been created.
after that you have run the command as
1 | update-database |
now your database has been created you just open the sqlserver and check them database has created or not.if the database is created after we will do the crud functionality.
Crud.EF
Select the Crud.FF
Create the folder
Right click the Crud.FF add-New folder and name it as Services
Inside the Services folder have to create two classes which are GenericDataService.cs and NonqueryDataService.cs
GenericDataService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | using Crud.domain.Services; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Crud.EF.Services { public class GenericDataService<T> : IDataService<T> where T : class { private readonly StudentContextFactory _contextFactory; private readonly NonqueryDataService<T> _nonQueryDataService; public GenericDataService(StudentContextFactory contextFactory) { _contextFactory = contextFactory; _nonQueryDataService = new NonqueryDataService<T>(contextFactory); } public async Task<T> Create(T entity) { return await _nonQueryDataService.Create(entity); } public async Task<bool> Delete(T entity) { return await _nonQueryDataService.Delete(entity); } public async Task<T> Get(int id) { using StudentDBContext context = _contextFactory.CreateDbContext(); return await context.Set<T>().FindAsync(id); } public async Task<IEnumerable<T>> GetAll() { using StudentDBContext context = _contextFactory.CreateDbContext(); return await context.Set<T>().ToListAsync(); } public async Task<T> Update(T entity) { return await _nonQueryDataService.Update(entity); } } } |
NonqueryDataService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using Microsoft.EntityFrameworkCore.ChangeTracking; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Crud.EF.Services { public class NonqueryDataService<T> where T : class { private readonly StudentContextFactory _contextFactory; private readonly NonqueryDataService<T> _nonQueryDataService; public NonqueryDataService(StudentContextFactory contextFactory) { _contextFactory = contextFactory; } public async Task<T> Create(T entity) { using StudentDBContext context = _contextFactory.CreateDbContext(); EntityEntry<T> createdResult = await context.Set<T>().AddAsync(entity); await context.SaveChangesAsync(); return createdResult.Entity; } public async Task<bool> Delete(T entity) { using StudentDBContext context = _contextFactory.CreateDbContext(); context.Set<T>().Remove(entity); await context.SaveChangesAsync(); return true; } public async Task<T> Update(T entity) { using StudentDBContext context = _contextFactory.CreateDbContext(); context.Set<T>().Update(entity); await context.SaveChangesAsync(); return entity; } } } |
StudentCrudServices.cs class have to inhert ICrud class
this class consist of all the crud operation and validations.
StudentCrudServices.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | using Crud.domain.Model; using Crud.domain.Services; using Crud.EF.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crud.EF { public class StudentCrudServices : ICrud { private readonly IDataService<Student> _crudServices; public StudentCrudServices() { _crudServices = new GenericDataService<Student>(new StudentContextFactory()); } public async Task<Student> AddBrand(string stname, string course) { try { if (stname == string.Empty) { throw new Exception("Student Name Cannot be Empty"); } else { Student br = new Student { stname = stname, course = course }; return await _crudServices.Create(br); } } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<bool> DeleteBrand(int id) { try { Student delete = await SearchBrandbyID(id); return await _crudServices.Delete(delete); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<ICollection<Student>> ListBrands() { try { return (ICollection<Student>)await _crudServices.GetAll(); } catch (Exception ex) { throw new Exception(ex.Message); } } public Task<Student> SearchBrandbyID(int ID) { try { return _crudServices.Get(ID); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<ICollection<Student>> SearchBrandByName(string stname) { try { var listbrand = await ListBrands(); return listbrand.Where(x => x.stname.StartsWith(stname)).ToList(); } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<Student> UpdateBrand(int id, string stname, string course) { try { Student br = await SearchBrandbyID(id); br.stname = stname; return await _crudServices.Update(br); } catch (Exception ex) { throw new Exception(ex.Message); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | <Window x:Class="Crud.UI.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Crud.UI" mc:Ignorable="d" Title="Student Crud Application" Height="450" Width="800"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="25"></ColumnDefinition> <ColumnDefinition Width="28.261"></ColumnDefinition> <ColumnDefinition Width="321.739"/> <ColumnDefinition Width="10"></ColumnDefinition> <ColumnDefinition Width="270"></ColumnDefinition> <ColumnDefinition Width="25"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="25"></RowDefinition> <RowDefinition Height="217*"></RowDefinition> <RowDefinition Height="167*"/> <RowDefinition Height="25"></RowDefinition> </Grid.RowDefinitions> <StackPanel Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Margin="0,167,0,0" Grid.RowSpan="2" /> <StackPanel Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2" Grid.RowSpan="2"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="250"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="25"></RowDefinition> <RowDefinition Height="5"></RowDefinition> <RowDefinition Height="25"></RowDefinition> <RowDefinition Height="5"></RowDefinition> <RowDefinition Height="25"></RowDefinition> <RowDefinition Height="25"></RowDefinition> </Grid.RowDefinitions> <Label Content="Student ID" Grid.Row="0" Grid.Column="0" > </Label> <TextBox x:Name="txtStudentID" Grid.Row="0" Grid.Column="1" /> <Label Content="Student name" Grid.Row="2" Grid.Column="0" > </Label> <TextBox x:Name="txtStudent" Grid.Row="2" Grid.Column="2" /> <Label Content="Course" Grid.Row="4" Grid.Column="0" > </Label> <TextBox x:Name="txtCourse" Grid.Row="4" Grid.Column="2" /> <!--Button--> <StackPanel Grid.Row="12" Grid.ColumnSpan="2" Orientation="Horizontal" > <Button Width="50" Content="Add" x:Name="ButtonAdd" Margin="10 0 10 0" Click="ButtonAdd_Click" /> <Button Width="50" Content="Update" x:Name="ButtonEdit" Margin="10 0 10 0" /> <Button Width="50" Content="Search" x:Name="ButtonSearch" Margin="10 0 10 0" /> <Button Width="50" Content="Delete" x:Name="ButtonDelete" Margin="10 0 10 0" /> <Button Width="50" Content="List" x:Name="ButtonList" Margin="10 0 10 0" /> </StackPanel> </Grid> </StackPanel> <DataGrid Grid.Column="4" Grid.Row="1" x:Name="DataGridBrand" Margin="5,5,5,5" Grid.RowSpan="2"> </DataGrid> </Grid> </Window> |
After that double click the MainWindow.xaml.cs for writting the code
MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | using Crud.domain.Model; using Crud.EF; 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 Crud.UI { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private readonly StudentCrudServices _crudServices; public MainWindow() { InitializeComponent(); _crudServices = new StudentCrudServices(); ButtonAdd.Click += ButtonAdd_Click; ButtonList.Click += ButtonList_Click; DataGridBrand.SelectionChanged += DataGridBrand_SelectionChanged; ButtonEdit.Click += ButtonEdit_Click; ButtonDelete.Click += ButtonDelete_Click; ButtonSearch.Click += ButtonSearch_Click; } private async void ButtonEdit_Click(object sender, RoutedEventArgs e) { try { if (txtStudentID.Text != string.Empty && txtStudent.Text != string.Empty) { await _crudServices.UpdateBrand(int.Parse(txtStudentID.Text), txtStudent.Text, txtCourse.Text); throw new Exception("Data Successfully Updateddd"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { await ListBrands(); } } private async void ButtonDelete_Click(object sender, RoutedEventArgs e) { try { if (txtStudentID.Text != string.Empty && txtStudent.Text != string.Empty && txtCourse.Text != string.Empty) { await _crudServices.DeleteBrand(int.Parse(txtStudentID.Text)); throw new Exception("Data Successfully Deleteddd"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { await ListBrands(); } } private async void ButtonSearch_Click(object sender, RoutedEventArgs e) { var SearchName = await _crudServices.SearchBrandByName(txtStudent.Text); DataGridBrand.ItemsSource = SearchName.ToList(); } private void DataGridBrand_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { var activelist = (Student)DataGridBrand.CurrentItem; if (activelist != null) { txtStudentID.Text = activelist.id.ToString(); txtStudent.Text = activelist.stname; txtCourse.Text = activelist.course; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private async void ButtonList_Click(object sender, RoutedEventArgs e) { try { await ListBrands(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private async Task ListBrands() { var brandList = await _crudServices.ListBrands(); DataGridBrand.ItemsSource = brandList.ToList(); } private void ButtonAdd_Click(object sender, RoutedEventArgs e) { try { _crudServices.AddBrand(txtStudent.Text, txtCourse.Text); throw new Exception("Data Successfully Addedd"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { txtStudentID.Clear(); txtStudent.Clear(); txtCourse.Clear(); txtStudentID.Focus(); } } } } |