Override or hide property in partial class
I have read around quite a bit now and think that the following is not doable, but I would like to have confirmation from experts if possible and possibly advice on a "best" workaround.
In all the auto-generated linq-to-sql classes I end up doubling up on all properties to carry out checks on the values as they are set, say, I have a Person class with a Name property on which I end up doing:
public partial class Person
{
public string Name
{
get { return this._Name; }
set
{
if (!string.IsNullOrEmpty(value))
{
value = value.trim();
this._Name = value.Substring(0, Math.Min(value.Length, 200));
}
else
throw new InvalidOperati开发者_Go百科onException("Person name cannot be blank");
}
}
}
Simple check to ensure that when I persist to the database the name won't exceed the maximum length.
Which means I end up doubling up on nearly every single property from the auto-generated class and that makes a massive mess because they end up all being named something similar.
I tried adding a layer on top of the partial classes by making my own representation of the objects, but ran into problems when instantiating classes which depended one on the other... Say a person has a company, you instantiate person and its company which instantiates persons for the company, which reinstantiates companies etc...
Is there some "good" way to do what I am trying to do with the partial classes? If not, what are the alternatives that work best? Maybe inheriting every single partial class and overriding the properties? Using the OnChange events to perform the checks?
The recommended approaches are laid out in ScottGu's blog post here: http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx
and again, here
http://geekswithblogs.net/AzamSharp/archive/2008/03/30/120875.aspx
Also, you might want to look into moving from L2S to Entity Framework, which provides more robust validation support.
It sounds to me like your trying to make linq to sql do something it was never intended to do. When I run into situations like this I start looking for a tool/library/orm etc that is better suited for what I am trying to accomplish
精彩评论