Jerry Nixon @Work: LINQ to SQL Entity Base Class

Jerry Nixon on Windows

Monday, June 8, 2009

LINQ to SQL Entity Base Class

So many things in LINQ to SQL are cool. But the handling of entities in a asp.net application drove me crazy. It was either the entity is already attached, different then the one in the database, or created with a different data context. So, I created my own base class that handles this and some other common issues with LINQ.
 
Let’s discuss.
 
The entities created by LINQ to SQL do not have a base class. As a result, it is VERY easy for them to inherit from anything, including my custom base class. Because the entity classes are already partial classes, all you need to do is create another class with the same name and the partial keyword. In addition, reference System.Runtime.Serialization. Done.
 
This is truly my gift to you. It took me a good 3 days to finally get all this working right. And the dynamic lambda stuff there (see the SelectOne() method) – that alone might make all this worth it. Nonetheless, it’s all yours. You’re welcome. :)
 
Here’s the code to get you there (entity name = “Term”): http://www.codepaste.net/cg2imz
 
The biggest benefit is the Update methods:
image
 
And the most difficult part is this:
image
 
Just remember:
E = the type of the entity itself. It’s a little circular, but it is necessary
C = the type of the data context you are using
T = the data type of the single column, primary key (like Integer)
 
The coolest part is this:
image
 
That cool part constructs the lambda expression at runtime instead of design time. It might, just might, be the coolest thing I have written in a long while. But I would have to think about that.
 
It’s finally worth pointing out that I assume the data context you are using is in the Program class. You will want to update this to however you use it.
image
 
Enjoy.