Wednesday, March 26, 2008

Extending Linq To Sql Entity Classes

A common question regarding the Linq to Sql is how to extend the base entities created by the Linq to Sql generator.

When you create a class using the DBML designer (yuck!) you get a class with 10,000 lines of code hiding under a designer.cs file.


Avoid mucking with this designer file at all costs! Any changes to your schema will regenerate the classes in this file and wipe out all of your changes.

So how do you extend it?

Using partial classes.

When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
Here is a sample class definition created by the MSLinqToSQLGenerator.

public partial class Customer: INotifyPropertyChanging, INotifyPropertyChanged
{

}

In another class file you can extend this partial class as needed. I always recommend creating a new class file to hold your partial class.

public partial class Customer
{

}

Your external class can implement interfaces cleanly.

public interface IEntityObject
{
bool IsDirty();
bool IsNew();
}

public partial class Customer: IEntityObject
{
#region IEntityObject Members

public bool IsDirty()
{
throw new NotImplementedException();
}

public new bool IsNew()
{
throw new NotImplementedException();
}

#endregion
}

Casting the Customer object to an IEntityObject is now valid.

You can also inherit from a base class.

public abstract class EntityBase
{
public abstract void Validate();
}
public partial class Customer : EntityBase
{
public override void Validate()
{
throw new NotImplementedException();
}
}

Done.