Saturday, March 1, 2008

How to use the Unplugged LINQ to SQL Generator

As Chris Rock pointed out, the first release of our Code Project custom tool for LINQ to SQL code generation lacks any usage documentation. We'll fix this on the next few days, meanwhile these are the basic instructions:

Install the Custom Tool

After building (VS 2008) the ULinqGen project, you may either register the assembly with regasm, or build and run the setup project. Then you should close the IDE (all VS2008 instances) and reopen it to make the new custom tool available.

Code a generic Data Context class in your project

It may be as simple as this:
    public class MyDataContext : DataContext
{

private static System.Data.Linq.Mapping.MappingSource
mappingSource = new AttributeMappingSource();

public MyDataContext(string connection) :
base(connection, mappingSource)
{
}
}

Associate each DBML to the custom tool

On the project explorer, for each model in which you want to use this tool, set the "Custom Tool Name" property to "ULinqToSQLGenerator"

Get tables from your generic data context and you are ready to LINQ

Assuming your DBML has an Invoice entity with InvoiceItem children and a Customer foreign relation, it may look as this:
    MyDataContext dc = new MyDataContext( myConnectionString);
Table invoices = dc.GetTable<Invoice>();

var results = from i in invoices
where i.IsApproved
&& i.Customer.FirstName.StartsWith("John")
&& i.InvoiceItems.Count > 2
order by i.ApprovalDate
select i;
return results.ToArray();

From here it's up to you!

2 comments :

Matthew Hunter said...

Good work guys, just wondering though in what way you were planning to do the change tracking on the client side?

I've got been working on some bits on pieces using a base class to control trange tracking + a little reflection.

My current method involves having each entity know it's state (new, modified, dirty, deleted) when disconnected, the it's a simple matter attaching them all based on this. So I don't have any "clientcontext" so to speak.

Are you planning on doing something similar? Or are you going for more of a "clientcontext" method, where you attach the objects to this.

Benjamin Eidelman said...

That's a big question we let unanswered (on purpose :)), many people are creating different disconnected change tracking implementations in one of those ways:

- ClientContext (a disconnected serializable context with a portable change set)
- Entities with state (alla DataRow.RowState)

As you, We are taking the second approach (entities with state).
The reasons for this worth another blog entry, I'll publish one about this very soon.

We'll be glad of reading your comments about it!

Regards,