This post will show you how to perform crud operations on master details with ease. It also shows you how you can embed your business validation rules within the Entity Framework classes. Also give insight of WPF DataGrid
I got a overwhelming response for my post , CRUD Operations using Ado.net Entity Framework. Continuing further on this I wanted to show some advanced features of ado. net entity framework. In this post I discuss about how you can do CRUD Operations on master details tables. Perform some business validation rules using Entity Framework partial classes both at the field level as well as on the record level. Sounds interesting then continue read on. This post is the Part two of Entity Framework. I strongly recommend all the readers to read the Part one post before.
MASTER DETAILS CRUD OPERATIONS
I continue from where I stopped on my last post. We will be using the same Employee table. For this post I have added new table in the database called Languages. This tables contains the information about the languages that are known by the employee. It is a detail table to the master table , employee. The employee id is the reference key here.
As shown in the figure above the UI is very simple. I have used WPF DataGrid , which is included in WPF Toolkit. This DataGrid control is very powerful. It has rich object model with many events. When you are in Add Mode you can press TAB key to insert a new row and when you are in Update Mode you can you use DELETE key to remove the row from the datagrid. Based on these actions it has also the corresponding events attached. When adding I use the following event
Private Sub DgLanguages_RowEditEnding(ByVal sender As Object, ByVal e As Microsoft.Windows.Controls.DataGridRowEditEndingEventArgs) Handles DgLanguages.RowEditEnding End Sub
If e.EditAction = Microsoft.Windows.Controls.DataGridEditAction.Commit Then
The above code uses RowEditEnding event of Wpf DataGrid , if you are committing the row that is pressing the TAB key I add new language in the Languages list by doing type casting of the Row datacontext. Similarly when the user press DELETE key I have used DataGrid Unloading Row event. Here I remove the the language from the language list.
Private Sub DgLanguages_UnloadingRow(ByVal sender As Object, ByVal e As Microsoft.Windows.Controls.DataGridRowEventArgs) Handles DgLanguages.UnloadingRow
So that was the additional code to my previous post.
Dim Language As Languages
Language = e.Row.DataContext
If Not Language Is Nothing Then
BUSINESS RULES VALIDATION WITH ENTITY FRAMEWORK
The coolest feature about the entity framework is that it can be extended through Partial classes. You can always add your custom code on the top of the default code generated by Visual Studio. If you would have worked with Entity Framework before you must be aware that Visual Studio generates .designer.vb or .designer.cs. This file can be seen under your .edmx file. If you have through look into this file you will observe that Visual Studio has generated one EntityContext class and the rest classes depends on the number of tables that you dragged and dropped on the designer surface of the edmx file. Each of this class can be extended as they are declared partial. And that is the catch , the rich object model of the entity framework exposes lot of events which can be handled by developer by creating the partial classes. If you want to use the field level validation then you can extend your Entity class. If you want the Record level validation then you can extend EntityContextClass. Let us take the example of each one by one. Suppose I want that the LastName field cannot be blank. I can use OnLastNameChanged event and check for the property variable. The code listing of the same is given below
Private Sub OnLastNameChanged()
If String.IsNullOrEmpty(_LastName) Then
MessageBox.Show("Last Name cannot be blank")
If you wish to initialize some property values when the form gets loaded. You can use constructor method. The below example initializes the salary property variable to 3000
Public Sub New()
_Salary = 3000
Now let us look at the record level validation. This validation can be applied on the Entities class. You need to attach the event handler for the SavingChanges Event. This is best place where you can implement all your business rules and ensure that only valid data goes into your database. Take a look at the code below.
Public Class EFDemoEntities
Private Sub OnContextCreated()
AddHandler Me.SavingChanges, AddressOf SaveRecord
Private Sub SaveRecord(ByVal sender As Object, ByVal e As EventArgs)
Dim ctx As ObjectContext
ctx = CType(sender, ObjectContext)
For Each objEntry As ObjectStateEntry In ctx.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added Or System.Data.EntityState.Modified)
If TypeOf objEntry.Entity Is Employee Then
Dim Emp As Employee
Emp = CType(objEntry.Entity, Employee)
If String.IsNullOrEmpty(Emp.FirstName) OrElse String.IsNullOrEmpty(Emp.LastName) Then
Throw New Exception("First Name or Last Name cannot be null")
Dim DuplicateLanguages As New List(Of String)
DuplicateLanguages = (Emp.Languages.GroupBy(Function(x) x.Language).Where(Function(y) y.Count > 1).Select(Function(z) z.Key)).ToList
If DuplicateLanguages.Count > 0 Then
Throw New Exception("Duplicate Languages not allowed")
The above code make a final check of all the business rules. Besides checking for the null values for the FirstName and LastName properties. I also perform an additional check that Languages in the detail section cannot be duplicated. This check is performed by Linq using GroupBy method.
Ado.net Entity Framework has lot to offer. It is very rich data access api. You need to learn more about it and use in all your applications. Hope you must have enjoy reading this post. Let me know your thoughts for it. Download the code from here.
Please rename the file extension from .doc to .rar. Also change the connectionstring in your app.config file.