DeeStackOverflow
DeeStackOverflow

Reputation: 2781

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 ?

Upvotes: 1

Views: 1337

Answers (3)

Dan J
Dan J

Reputation: 16708

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062600

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.

Upvotes: 0

A_Nabelsi
A_Nabelsi

Reputation: 2574

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.

Upvotes: 2

Related Questions