adamjcooper.com/blog

Enterprise Software Development in C#


IntelliSense Support for LINQ to SQL Mapping with External XML Files

Introduction

The fastest way to get database objects with LINQ to SQL is to simply build your objects and associated mappings using a tool like the LINQ to SQL designer in Visual Studio or a command-line tool like sqlmetal. However, both of these approaches assume a database-first development philosophy.

But what if you're using an objects-first development philosophy, such as Domain-Driven Design , and you want to hand-craft your objects first and then manually map them to a database later? Well, if you need that sort of fine-tuned control, there are two ways you can do this: 1) using inline code attributes to designate what .NET types and properties correspond to what tables and columns in your database, or 2) using an external XML file to specify the mapping from your .NET classes to your database, passing it to your data context at runtime.

Using inline attributes is nice if you want to see the database mappings right in the source code, but this is also its weakness. When working on a large project, I prefer to tease the object source code and the database mappings apart so that both are more focused and easier to maintain.

Microsoft has created an XML schema you can use to validate your custom LINQ to SQL mapping XML file, but apparently it is not included by default with Visual Studio 2008. As a result, there is no out-of-the-box IntelliSense support for custom LINQ to SQL XML mapping files. Fortunately, the fix is simple.

The Fix

All you need is a copy of Microsoft's LinqToSqlMapping.xsd file in your Visual Studio schemas folder (usually located at C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas). Then, just make sure you include the appropriate xmlns in your mapping XML file.

Then, just make sure your LINQ to SQL mappings file uses the xmlns http://schemas.microsoft.com/linqtosql/mapping/2007. Here's an example:

<?xml version="1.0" encoding="utf-16" ?>
<Database 
  xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"
  Name="MyDatabase">
  ...
</Database>

 

That's it. You should now have Intellisense support when manually mapping your LINQ to SQL classes in an XML file.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading





 
Powered by BlogEngine.NET 1.4.5.0 | Design by adamjcooper