Click here to Skip to main content
15,861,125 members
Articles / Web Development / ASP.NET
Article

PLINQO - Supercharge LINQ to SQL

Rate me:
Please Sign up or sign in to vote.
3.79/5 (6 votes)
17 Aug 2007CPOL6 min read 51.5K   143   17   8
PLINQO is a collection of CodeSmith templates that are meant to replace and extend the LINQ to SQL designers.

Overview

PLINQO, which stands for Professional LINQ to Objects, is a collection of CodeSmith templates that are meant to replace and extend the LINQ to SQL designers that are included with Visual Studio 2008.

Features

The templates have the following features:

  • Generate or update a LINQ to SQL DBML file from a database schema.
    • Includes all tables, stored procedures, functions, and views with the ability to exclude objects based on regex patterns.
    • Ability to automatically remove object prefix and suffixes (i.e. tbl_ and usp_).
    • DBML file can still be customized with the normal Visual Studio 2008 designer.
    • DBML file can be refreshed based on the current database schema without losing customizations. (See Safe Attributes)
  • Generation of the LINQ to SQL DataContext class.
  • Generation of the LINQ to SQL entity classes.
    • Generates one file per entity instead of one massive file.
    • Generates partial classes where custom code can be written and won't be overwritten.
    • Generated entity files are added to the project as code behind files to their corresponding custom entity files.
  • Generation of entity manager classes.
    • Adds customizable business rules engine to enforce entity validation, business and security rules.
    • Provides access to common queries based on primary keys, foreign keys, and indexes.
    • Common queries are exposed as IQueryable so they can be extended.
  • All templates can be customized to meet your needs.

Quick Start

Use the following steps to get started using the LINQ to SQL templates:

  1. Create a new Class Library project in Visual Studio 2008.
  2. Add a new CodeSmith project file to the Visual Studio project (Figure 1):

    Screenshot - SampleSolution.png

  3. Add a new Output to the project file for the Dbml.cst template (Figure 2):

    Screenshot - dbml.jpg

  4. Add another Output to the project file for the Entities.cst template (Figure 3):

    Screenshot - entities.jpg

  5. Optionally, add an Output for the Managers.cst template (Figure 4):

    Screenshot - managers.jpg

  6. Set the Sample.csp -> Output Options -> Add Outputs to Project to unchecked. The templates update the project for you.
  7. Finally, Generate the Outputs (Figure 5):

    Screenshot - SampleGeneratedSolution.png

Dbml.cst Template

The Dbml.cst template is used to create a LINQ to SQL DBML file. The file conforms to the Microsoft DbmlSchema.xsd schema. This is the same document that the LINQ to SQL designer uses. The generated DBML file from this template can also be edited from the LINQ to SQL designer.

The template will create a new file if it doesn't exist. If the file does exist, the template will read it in and update it. This allows you to make changes to the file and not have it overwrite if the template is re-run. However, only some of the attributes are safe from overwriting. Here is a list of safe attributes. They will be listed as an xpath.

Safe Attributes to change in the DBML file...

  • Database/@Class - The name of the DataContext class that will be generated.
  • Database/@EntityNamespace - The namespace for the entity classes.
  • Database/@ContextNamespace - The namespace for the DataContext class.
  • Table/@Member - The property name for the table in the DataContext class.
  • Type/@Name - The name of the entity class.
  • Column/@Member - The property name for the column in the entity class.
  • Column/@Storage - The private field LINQ to SQL will use to assign values to.
  • Association/@Member - The property name for this association.
  • Association/@Storage - The private field LINQ to SQL will use to assign values the association to.
  • Function/@Method - The name of the method for the database procedure.
  • Parameter/@Parameter - The method argument name that maps to the database procedure parameter.

Warning: Be aware that the template will drop tables, columns and associations that it did not find in the database.

Properties on the Dbml.cst Template

PropertyDescription
CleanExpressionList of regular expressions to clean table, view, column and procedure names. Any matched text found will be removed from the name.
IgnoreListList of regular expressions used to ignore tables, views and procedures when generating mapping. Any database objects that match one of these regular expressions will be ignored.
IncludeFunctionsInclude stored procedures and user functions in mapping.
IncludeViewsInclude views in mapping.
SourceDatabaseThe source database to generate the DBML file for.
ContextNamespaceThe namespace to use for the context class file.
EntityNamespaceThe namespace to use for the entity class files.
DbmlFileThe path to the DBML file to generate.

Entities.cst Template

The entities template generates the entity classes needed by LINQ. The classes are generated from a DBML file. You can modify the names for classes and properties by editing the DBML file. See Dbml.cst for a list of safe attributes to change in the DBML file.

The template will generate two files for every Type in the DBML file. One file will be the generated partial class that cannot be changed as it is overwritten when the template is re-run. It will have the following file name... <entity>.Generated.cs.

The second file is a partial class that can be modified as it will not be re-generated. You can implement the partial methods in this file. Some partial method stubs are created by default. This file will be named... <entity>.cs.

If you set the project file property on the template, the generated files will be added to the project. The file that cannot be modified will be hidden under the file that can be changed.

Properties on the Entities.cst Template

PropertyDescription
DbmlFileThe path to the DBML file used to generate the entities from.
OutputDirectoryThe folder to save the generated files.
ProjectFileThe Visual Studio project file to add the generated files to.

Managers.cst Template

The manager template is for helping you get started with business logic for the LINQ entities. The managers will have common queries that are created from keys and indexes on the table. The manager will also have rules for the entity properties to make sure required fields are not null and that the length of a string does not exceed the max length the column allows.

The template works by creating a second DataContext class that has a Manager property. The manager will then have a property for each entity that has a manager. Here is a sample of the syntax for using the managers:

C#
SampleManagerContext db = new SampleManagerContext();
// use the primary key
Task task = db.Manager.Task.GetByTaskID(taskId);
// use a foreign key
var myTasks = db.Manager.Task.GetByAssignedID(userId);
// the methods return IQueryable so you can add expressions
var openTasks = db.Manager.Task.GetByStatusID(statusId).OrderBy(t => t.CreateDate);

The manager also provides a business rules engine to your entities. In addition to the default validation rules that are generated, you can add custom rules by implementing the AddRules partial method in the custom entity class.

C#
static partial void AddRules()
{
  // Rule allows the Name property to be a max of 150 characters.
  RuleManager.AddShared<Task>(new LengthRule("Name", 150));
  // Rule that validates the value of the property using regex.
  RuleManager.AddShared<Task>(new RegexRule("Name", ".*"));
  // Rule allows only users in certain security roles to update.
  RuleManager.AddShared<Task>(new UpdateRule(
    new string[] { "Administrator", "Updaters" }));
}

Properties on the Managers.cst Template

PropertyDescription
SourceDatabaseThe source database to keys and indexes for generating the manager classes.
DbmlFileThe path to the DBML file used to generate the manager classes from.
ManagerContextNameThe class name of the DataContext that supports the managers.
ManagerDirectoryThe folder to save the generated manager files.
ManagerNamespaceThe namespace to use for the generated manager class files.
ProjectFileThe Visual Studio project file to add the generated files to.

Known Issues

  • The generated DataContext does not set the connection string like the LINQ to SQL designer.

Roadmap

  • Improve manager template
  • Unit test generation
  • Web service generation
  • ASP.NET, Winforms and WPF UI generation
  • Visual Basic support

History

  • 17th August, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionI am getting the following error when opening the file. Pin
Member 127809924-Feb-09 21:36
Member 127809924-Feb-09 21:36 
GeneralPLINQO and WCF Pin
TheCubanP21-Feb-09 10:56
TheCubanP21-Feb-09 10:56 
GeneralLooks very nice however.. Pin
devnet24728-Sep-07 22:18
devnet24728-Sep-07 22:18 
Hi,
I have to admit that I am new to Codesmith too and therefore I might be doing something wrong.
I have followed your example to the letter on the northwind Database but I get an error "Error loading Dbml"
File"
i am totally lost as i cannot see anything.
Any suggestions?

Also 1 limitation if you like is that you have to use the DBML file .Well where i work we have 800 tables and 4000 stored procedures ,both sqlMetal and yours fail miserably for various reasons in creating a dbml file.
Also it's unmanagable with so many table,therefore we would only generate classes.
Any suggestion on this?

Also it would be helpful if we could download a sample Solution where we see how it all works.
Would that be possible?

Thanks


thanks a lot

GeneralRe: Looks very nice however.. [modified] Pin
ie_richie16-Jun-08 17:12
ie_richie16-Jun-08 17:12 
QuestionPros and Cons? Pin
Galin Iliev [Galcho]19-Aug-07 2:20
Galin Iliev [Galcho]19-Aug-07 2:20 
AnswerRe: Pros and Cons? Pin
Paul Welter21-Aug-07 8:54
Paul Welter21-Aug-07 8:54 
GeneralRe: Pros and Cons? Pin
Galin Iliev [Galcho]29-Aug-07 4:49
Galin Iliev [Galcho]29-Aug-07 4:49 
GeneralRe: Pros and Cons? Pin
John'o27-Jan-09 3:30
John'o27-Jan-09 3:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.