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.