tags:

views:

27

answers:

1

I see a number of posts talk about rolling your own LINQ to SQL XML mapping file. Why would you do this instead of using SQLMetal or the designer built into studio? Is it because you want to work with your own POCOs?

+2  A: 

If you use the designer then you have no control over the generated classes. While this may be alright for many applications, it's not appropriate for all.

Probably the biggest single advantage to using an external mapping is that it breaks your model's dependency on Linq to SQL, so you could (for example) take the exact same model classes and use them with Entity Framework or NHibernate. Projects or assemblies which need to use the model don't pick up an unwanted dependency on the System.Data.Linq assembly.

Other things you might want to do are:

  • Include validation logic or other complex logic in property setters;
  • Use virtual properties (for proxying);
  • Decorate existing properties with other attributes (i.e. serialization);
  • etc.

None of these things are possible with generated code. You can extend via partial classes, but that only lets you add members, not change existing ones. You can change the designer-generated code, obviously, but your changes will just get overwritten.

As I mentioned, many projects don't need these things, but many projects do, and if yours is one that does then you'll outgrow the DBML designer and SqlMetal pretty quickly.

Aaronaught
Aaronaught, thank you for your response. In one example I saw they used SqlMetal to generate the XML file but not use the code file. I guess I am struggling with the relationship between the xml and code generated using in SqlMetal. I would prefer not to code up the xml file by hand. Is it okay to use a tool like SqlMetal or CodeSmith to generate the xml map?
dc
@dc: It is absolutely okay. The reason for using an external mapping is so you can decouple the model from Linq to SQL. The mapping itself has no meaning outside of Linq to SQL so it's normal and expected for this to be generated. I would always try to avoid writing error-prone XML by hand if there are other options.
Aaronaught