Solved

Validation in Linq to Sql

Posted on 2011-03-18
6
459 Views
Last Modified: 2012-05-11
Hi

Im using C#, ASp.net and Linq to Sql in my project

i have a partial method to validate my field, it works well but when I thow the exeption it shows me the ugly ASP error page, I would like to show this message in a ValidatorSummary , is this possible?
public partial class Oficios
{

    partial void OnNumPropuestaChanging(string value)
    {

        using (ModuloProgramacionDataContext db = new ModuloProgramacionDataContext())
        {

            var query = from p in db.Oficios
                        where p.NumPropuesta == value
                        select p;
            if (query.Count() > 0) throw new Exception("The field already exist in the database");
        
        
        }


    }

Open in new window

0
Comment
Question by:Veljean
6 Comments
 
LVL 10

Expert Comment

by:John Claes
ID: 35167165
You should Catch all your exceptions at the code behind your page and do something with them.
Every exception that is not catched will generate the "ugly" aspx page.

so add the message to the Validator summery in the Catch and show it then

poor beggar
0
 
LVL 1

Author Comment

by:Veljean
ID: 35167219
do you have an example ?
0
 
LVL 11

Expert Comment

by:Kusala Wijayasena
ID: 35167417
0
ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 
LVL 11

Accepted Solution

by:
SAMIR BHOGAYTA earned 250 total points
ID: 35167711
Hello,

LINQ to SQL Classes might not look like business objects but you can make them perform business rules validation. Let's say that you have a class called "Person". Person has FirstName, LastName, DOB (Date of Birth) etc. Now, you don't want two persons to have the same firstname or the lastname ( I know kinda weird requirement). You can use the OnFirstNameChanging method to implement the condition for same first name. Here is the code:

   partial void OnFirstNameChanging(string value)
        {
            // check if the firstname already exists in the database!
            SchoolDataContext school = new SchoolDataContext();

            var query = from p in school.Persons
                                  where p.FirstName == value
                                  select p;

            if (query.Count() > 0) throw new Exception("FirstName already exists in the database");
        }

Now, if the same first name already exists in the database then an exception is thrown. You can do the same thing for last name property.

 partial void OnLastNameChanging(string value)
        {
            SchoolDataContext school = new SchoolDataContext();

            var query = from p in school.Persons
                        where p.LastName == value
                        select p;

            if (query.Count() > 0) throw new Exception("LastName already exists in the database");
        }        

You can also use the OnValidate method of the Person object. In the following code I am checking that if the address has already been added.

  partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            SchoolDataContext school = new SchoolDataContext();

            if (action == System.Data.Linq.ChangeAction.Insert)
            {
                foreach (var address in this.Addresses)
                {
                    var query = from a in school.Addresses
                                where a.Street == address.Street
                                && a.PersonID == this.PersonID
                                select a;

                    if (query.Count() > 0) throw new Exception("Address already exists");
                }
            }
        }

If your requirment was that two persons cannot have the same FirstName and LastName then you should have used the OnValidate event.
0
 
LVL 1

Author Comment

by:Veljean
ID: 35167734
samirbhogayta

thanks for your tips, but my problem is I dont know what to do with the new Exception and avoid the ugly ASP error page, how you handle this errors?
0
 
LVL 10

Assisted Solution

by:John Claes
John Claes earned 250 total points
ID: 35178949
Veljean:

Look for information about the Try Catch blocks


Example

try
{
int a = 0;
int b = 10;
int c = b / a;  // this wil generate a Divide by Zero exception
divideTextbox1.Text = c;
}
catch (Exception exception)
{       // here we'll catch all exceptions and try to do something with them.
        // For this example I'm just going to show the ErrorMessage in an Label

       errorLabel.Text = exception.Message;
}



This will not show the ugly page but will remain on the normal page and show the error message

regards

poor beggar
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question