LINQ tutorial Part -VI

Validation in Linq (Business Logic) :-

As a programmer my first intention is to make a bug free code for that one of the part is data validation.What ever we want to insert /Update in database need to check.

For this we use data validation. With linq we can refine data in mainly two way. The first and basic way in which we do not have to do so much is Schema.

What ever OR mapping is done. The schema handle the database type which require to save in database. By this a user can not insert invalid datatype in DataBase.

Second and another important aspect is using validation rules or custom validation. This can be handle in two way

1) custom property validation support.

This can be understand by below example suppose I want to insert email address in database with proper email format. But if there is no validation for format check then user can insert and data in email field for this purpose we require cutome property validation.

As the class genrated with LINQ to sql is partial class so we can use it any where we want with just partial class use.

Imports system

Imports system.text.RegularExpression

Partial Class Customer

Private Sub OnstrEmailChanging(ByVal value As String)

Dim regMailEx As New System.Text.RegularExpressions.Regex(“^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$”)

Dim matchExp As System.Text.RegularExpressions.Match

matchExp = regMailEx.Match(value)

If matchExp.Success =false Then

Throw new applicationException (“e-mail is not valid!”)

end if

End Sub

End class

In the above way we can validate a entry. Main benefit of this we do not have to write on each page and call validation. Its works automatically when user changed the Email.

Another is custom entry object validation.

In this suppose you want to compare two or more than two different object or some other logic then we can use this it can be handle is partial class with onValidate method.

As shown below.

Private Sub OnValidate(ByVal action As System.Data.Linq.ChangeAction)If action = Data.Linq.ChangeAction.Insert OrElse action = Data.Linq.ChangeAction.Update Then

if Me.blnActive = true AndAlso Me.datActiveDate is nothing then

Throw New applicationException (“Activation date is required!”)

End if

End If

End Sub

in this way we can use validation.

So enjoy coding.

Thanks

Rajat

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s