views:

584

answers:

2

Hi,

In our project we have a standard auto-generated designer.cs file, linked to a DBML file, that contains all our object classes that map onto our database tables.

We want to pass these objects directly through a WCF Service and so they need decorating with the [DataContract] and [DataMember] attributes where appropriate. What is the best approach to doing this so the changes won't get wiped out when the designer.cs file is re-generated upon a change to the database scheme or some other change.

Partial classes are an option, but if the property I want to decorate with the DataMember attribute is already defined in the autogenerated designer.cs file then I can't add the same property definition to the partial class as this means the property will have been defined twice.

Thanks

Robin

A: 

The dbml files give partial classes, so you can create a new .cs file, define the partial class that you want to extend, and then decorate that with the attributes that you want. For instance if you have a generated data context that looks like

public partial class MyDataContext : System.Data.Linq.DataContext { ... }

you can define the following in a separate .cs file:

[DataContract] public partial class MyDataContext { ... }

This way you can extend the generated classes without worrying about them being overwritten when your dbml file is re-generated.

Mike Comstock
+2  A: 

Setting the DBML serialization mode to unidirectional will decorate the classes and a number of the members with the required attributes however it will ignore some of the associations to avoid circular references that were a problem prior to SP1.

If you want those too check out my LINQ to SQL T4 template that provides full SP1 compatible DataContract attributes (uncomment the line data.SerializationMode = DataContractSP1 in the DataClasses.tt file) as well as letting you customize any other parts of the DBML to C#/VB.NET code generation process.

DamienG