views:

44

answers:

2

When using LINQ-to-SQL or Entity Framework, I can easily generate a class for each table which takes care of the CRUD basics:

Info info = new Info();
info.Title = "testing";
db.Infos.InsertOnSubmit(info);
db.SubmitChanges();

And when I make structural changes to a database table, I can easily regenerate the table's model class (simply deleting it in the designer and dragging the table to the designer again). However, this of course overwrites everything that was in the class.

So in order to add extra functionality to each class which does not get deleted when I regenerate the model, I find myself having an extra model class for each table, hence two data layers in effect.

Is this common practice or is there a way to add functionality to the generated classes which does not get overwritten upon regeneration of the classes?

+5  A: 

Create a partial class with the same name (in a different source code file) and put whatever extended functionality you want there.

liggett78
thanks this works very well
Edward Tanguay
+2  A: 

As described? No, its not.

You deal with the problem by adding extra functionality by using partial classes. The partial classes go in a separate file so that when you delete and recreate the class in the designer your code remains and just gets attached as if by magic.

So, if you have a model:

MyDataClasses.dbml

Which in turn has files:

MyDataClasses.dbml.layout
MyDataClasses.designer.cs

You add the following file (Visual Studio will do this for you if you do "View Code" on the .dbml file):

MyDataClasses.cs

In this you can extend the DataContext to add behaviour when modifying data:

partial void InsertBooking(Booking instance)
{
    instance.LastModified = DateTime.Now;
    if (this.AuditUserID.HasValue)
    {
        instance.LastModifiedByID = this.AuditUserID;
    }

    this.ExecuteDynamicInsert(instance);
}

partial void UpdateBooking(Booking instance)
{
    instance.LastModified = DateTime.Now;
    if (this.AuditUserID.HasValue)
    {
        instance.LastModifiedByID = this.AuditUserID;
    }

    this.ExecuteDynamicUpdate(instance);
}

And the individual classes to add behaviour, calculated fields, etc. If you take something like ASP.NET Dynamic Data where you can also add annotations and classes for Meta Data this can get quite complex.

Murph