Posts in category .net - page 20

LINQ to SQL details, issues and patterns

LINQ to SQL (formerly called DLINQ) is a simple object-relational mapper (ORM) scheduled for .NET Framework 3.5/Visual Studio 2007 (Orcas).

On projects with new data I’m keen on keeping the tables and classes as similar as possible and so the limited functionality of LINQ to SQL really appeals to me.

Sure for larger applications or where legacy data does not inspire great classes then a more advanced ORM with better mapping facilities can outweigh the disadvantages and learning curve imposed by another layer of abstraction. Microsoft have that covered with LINQ to Entities which will ship post-Orcas because of the immaturity of the the designer and advanced scenarios.

While prototyping I’ve come up with a few oddities that deserve documenting somewhere. Here they are in not-quite-FAQ format.

What SQL is this query or operation generating?

Set the Log property of your DataContext object to Console.Out.

What objects are generated and how do I extend them?

MyDataContext : DataContext

Represents a users view of the database and is generated by designer/SQLMetal exposing a property for each table being mapped.

Can be extended by writing your own partial class or sub classing.

MyEntity / T

Represents an entity for each row in the associated table and is generated by designer/SQLMetal exposing a property for each field being mapped which is also decorated with attributes that specify the underlying field name and type.

Can be extended by writing your own partial class, sub classing or providing a super-class.

No classes are generated for the tables themselves, instead the generic class Table uses the attribute information from the entity objects (cached via various metadata classes such as MetaTable).

What patterns does LINQ to SQL use?

Thankfully ActiveRecord is ignored and a more flexible approach is used. It basically provides one class for the database and one for each type of entity (because of inheritance, there could be more than one type of entity per table).

I’ve yet to delve deep enough into the classes and patterns to find good matches but a brief look reveals the following possibilities:

  • RegistrySystem.Data.Linq.DataContext
  • Unit of WorkSystem.Data.Linq.DataContext
  • Identity MapSystem.Data.Linq.IdentityManager
  • Table Data GatewaySystem.Data.Linq.Table<T>
  • Query ObjectSystem.Data.Linq.DataQuery<T>
  • Metadata MappingSystem.Data.Linq.Provider.Meta*, System.Data.Linq.*Attribute, System.Data.Linq.Mapping.*

How do I persist changes?

Call the SubmitChanges method on your DataContext object.

What causes the error “Row not found or changed” when submitting changes?

By default LINQ to SQL creates UPDATE statements that include every field as it was when read in the WHERE clause and not just the primary key as you might expect. The upshot is that if the record has changed since it was loaded it will not find it.

However, there are also a couple of scenarios where it won’t find the record even if it hasn’t changed:

  • If the data range/precision of the .NET type can’t exactly hold the value in the SQL table (e.g. DateTime)
  • If the table schema doesn’t exactly match the mapping (e.g. a column’s null-ability changing)

If in doubt remove the table from your LINQ schema diagram and drag a fresh copy back in from your database using the Server Explorer pane.

Why does the OnPropertyChanging event use the PropertyChanged event handler delegate?

OnPropertyChanging does indeed seem to be using the PropertyChangedEvent and PropertyChangedEventArgs that OnPropertyChanged use.

Being that PropertyChangingEvent and PropertyChangingEventArgs exist I would assume this is a bug within the designer/SQLMetal in beta 2.

What database vendors are supported?

SQL Server 2000, 2005, 2008 and SQL-CE are currently included.

Why do queries against a table return entities that do not match the query?

This occurs when entity objects in memory are out-of-step with data in the database.

The query is executed against the SQL server and for each matching record it either creates and entity object or uses the cached one it already has.

Therefore it is possible your result set will:

  • not include matching entities because the database indicates they do not (database changed or do not exist)
  • include entities that do not match because the database indicated they did (database changed or object changed)

Why is memory consumption so high?

LINQ to SQL tends to burn more memory than you might be expecting because of the multiple objects and aggressive caching in place.

Should I share a DataContext between users?

Web applications, web services and middle-tiers often share objects between potential users and requests. It is worth bearing in mind that a DataContext is not well suited to sharing between users because:

  • Entities are cached indefinitely
    • High memory use as every entity is eventually loaded to memory
    • Entities to be out-of-date if the data can be updated elsewhere (triggers, imports, background jobs)
  • DataContext.CommitChanges persists all objects changed via that DataContext
    • Difficult to determine a safe point to commit User A’s completed entities without committing User B’s incomplete entities
  • DataContext’s Table creation is not thread safe
    • Accessing a table for the first time on two threads could cause the DataContext to create one instance of a Table whilst creating another for the same and resulting in the latter being kept but the former being returned to one of the callee’s.

A DataContext is therefore best suited for either a single-user application, per-session or per-request.


ActiveRecord, the ugly design pattern

I first encountered the Gang of Four Design Patterns book back in 2001 when a friend lent me a copy. I didn’t immediately get it, most likely because my object oriented experience up to that point consisted primarily of small Delphi applications.

In the last few years I’ve been working on much larger systems and have come to appreciate design patterns enough to get my own copy and also to invest in Martin Fowler’s excellent Patterns of Enterprise Architecture which provides higher-level patterns aimed at large data-driven applications.

One of the design patterns presented, and indeed a core component of the Ruby on Rails framework, is that of the ActiveRecord which attempts to provide object-relational mapping.

It achieves this by specifying a single class per database table where instances of that class represent a row in the table – exposing a property for each field the row has in the database. Each ActiveRecord instance is therefore effectively a domain/business object.

So far so good but then the ActiveRecord pattern ignores the single responsibility principle by specifying that the object should also include a bunch of static methods for managing the table’s contents and retrieving instances.

What you end up with is one object with two distinct responsibilities separated by nothing but the static keyword. Static methods and fields can serve a useful purpose but dividing up responsibilities isn’t one of them and neither is to provide global-like access across your application (Singleton abusers take note).

I can think of at least two reasons why gluing two candidate objects into one physical one using the ‘static’ split causes ActiveRecord to suffer with problems:

Multiple connections

Sometimes an application requires connections to more than one database (e.g. reporting, aggregation, upgrading tools, per-user switching of database in a web application).

Static methods often rely on static fields which means you’re going to have trouble making the

data you’re going to have trouble making them behave like objects.

Inheritance mapping

There are three types of inheritance mapping techniques available.

  1. Concrete Table Inheritance – one table per concrete class containing columns for all fields of the class regardless of where they are declared
  2. Class Table Inheritance – one table per class in the hierarchy containing columns for fields of the class they are declared in only
  3. Single Table Inheritance – a single table for all classes in the hierarchy containing all columns for all possible sub-classes many of which will be null

Concrete Table is most likely where the tables created by the parent classes would have little or no value and Class Table where they do.

Single Table is what ActiveRecord implementations such as Ruby on Rails tend to use although quite how it works I’ve yet to discover… Does the parent class magically know enough about it’s child classes that it’s static methods can handle the update/select/delete? Can I ask the parent class for all objects and get a mixed collection back?


Fowler presents a number patterns as alternatives and many object-relational mapping (ORM) solutions including LINQ for SQL utilize them.


AnkhSVN 1.0 released (Subversion plug-in for Visual Studio)

Screenshot of AnkhSVN in action!

AnkhSVN 1.0 has been released!

If you use Visual Studio 2003 or 2005 and are currently either using the TortoiseSVN shell extension (or Subversion command line) then you would do well to see just how much more productive having source-control available from within the IDE can be.

Thanks go to Arild and mac gyver for all their hard work on this great open source project.

Hope you enjoy my icons too!


How to spot a Visual Studio 2005 SP1 installation

If like me you have a couple of machines, a few virtual machines and secondary installations such as Express editions (for XNA of course) you can easily loose track of which have been patched with service pack 1. Especially if you also messed around with the SP1 beta.

Help > About from Visual Studio 2005 can tell us – cryptically…

No service pack – Version 8.0.50727.42 (RTM.050727-4200)

Service pack 1 beta – Version 8.0.50727.363 (SP.050727-3600)

Service pack 1 – Version 8.0.5727.762 (SP.050727-7600)

Thanks to Rikkus and Gringod for providing their about dialogs!

Burge points out that clicking Show updates inside Add/Remove Programs reveals the SP1 update nested beneath Microsoft Visual Studio 2005 xxx Edition – although it doesn’t tell you if you still have the beta installed.