Search code examples
c#linq-to-sqldatacontextdatacontract

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 
                             { 
                               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 ?


Solution

  • 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.