LINQ to SQL is an ORM tool from Microsoft. In this article, we explore the essence of an 'LTS classes' file, the classes it generates, how it connects the object model to the database model... By understanding it, we can customize it into our own version of LTS classes which is easier to upgrade and more flexible.
AdventureWorksLT database is used in this article, but you can use whatever database you want.
After adding a new 'LTS classes' file (AdventureWorksLT.dbml) to your project and dragging tables from Server Explorer to the AdventureWorksLT.dbml tab, you will have a class diagram of your object model like this:
Now we can examine the essence of the file.
In Solution Explorer, expand AdventureWorksLT.dbml and open AdventureWorksLT.designer.cs, you can see many classes in this file. The first is AdventureWorksLTDataContext
, the DataContext
class is the core channel that you use to work with your database; the others are entity classes which are map back to your tables in the database.
You should also take a look at the mappings. Right click on AdventureWorksLT.dbml and open with XML Editor, we have something like this:
Now that you have an insight of the LTS file, you might notice that it's difficult to upgrade and not flexible. In my projects, I always separate the file into many parts (each class in its own file, put entity classes and data access classes in different namespaces,...), and I also customize the classes to utilize the power of inheritance, reuse, abstraction... I'm blogging about that in the next articles, but you can try separating the DBML file into a code file and a map file first: Open Visual Studio Command Prompt, navigate to the folder containing AdventureWorksLT.dbml and run this:
sqlmetal /code:awlt.cs /map:awlt.map AdventureWorksLT.dbml
You will have two new files in the same folder, they're a little different from what you've seen in the DBML file. Explore them for your own interest.
CodeProject