Transforming Linq To Sql DataContext objects to DataContract objects
I have DataContext classes generated from dbml. Once I get data from the database, I need to transform them into DataContract classes so that the objects can be sent via WCF.
One way to do this is like this:
using (var dc = new TestDBL2SDataContext(Settings.Default.TestDBConnectionString))
{
var myEmp = from rec in dc.Employees
select new MyDataContracts.Employee
开发者_C百科 {
FirstName = rec.Name.Substring(0,10)
};
return myEmp.FirstOrDefault();;
}
Is there a better way to do this via an XSD/XSLT file that I can define in my project and simply point to ?
Open the dbml file, select the designer and in the properties window set the Serialization Mode to Unidirectional, that's all you need to send the Employee records returned from the datacontext via WCF.
I hope that what you are looking for.
We've written Translator<FromDataModelType, ToDataContractType>
classes for this, and are using AutoMapper as a quick-and-painless way to accomplish the mapping between properties.
This assumes that you need to apply transformations to the DataContext classes, as you're doing by assigning a substring of Name
to FirstName
.
In the dbml designer, set the serialization mode to unidirectional. Job done.
If you need a slightly different DTO layer, maybe AutoMapper is a good option.
精彩评论