Friday, April 3, 2009

Customizing Entities in Linq to SQL

Linq to SQL is very powerful. There is a wonderful designer in Visual Studio 2008. It lets you just drag and drop tables onto the layout and it generates the entities for you. At first I though I would push my luke and see if I could edit the .dbml.designer.cs file. You sort of can, but ultimately, it will get overwritten the next time you open the designer and save the layout. I kept reading on the internet that you could customize these generated entities using a partial class. So, I looked in the .dbml.designer.cs file and wouldn't you know it, the entities are implemented as partial classes. But that still didn't help me at first. Then I saw some sample code that showed separate entities in the project file. These entities where named the same as the entities that were generated in the .dbml.designer.cs file. I didn't see any other connection between the two except that they were in the same namespace and assembly. I tried the same thing on my project. It worked. I did determine that it is important for the namespace to be the same for my classes and the generated classes. I don't know about the assembly have to be the same, but that is not something I am interested in this case. All you have to do is create a class in your own .cs file with the same name and use the key work partial in the class definition. public partial class Person { } Now you can customize (in this examle) Person how you like. This includes validation of properties, cross-property validation, etc. The partial classes defined in the .dbml.designer.cs file get executed first, and then your custom classes.

1 comment:

Daniel Gasca said...

It works perfect !! Thank You.