Search code examples
asp.netlinqentity-frameworkdata-bindingdatamapper

Tools for mapping business objects (DTO objects) from entities in asp.net mvc?


is there any tool or utility(mapper assembly) to construct business objects from entities(which are obtained from DB using linq -> sql , entity framework or whatever..)

in the absence of one , can anyone suggest the best way that can be accomplished rather can copy pasting the properties(what i'm doing right now) from the entity classes.?

vijay


Solution

  • You map to business objects by projecting. This works even if your POCO business objects have a different shape than your entities.

    var q = from dataObject in Context.DataObjects
            select new BusinessObject
            {
                Name = dataObject.Name,
                RelatedObjectName = dataObject.RelatedObject.Name, // works even if RelatedObject is null
                DirectChildren = from c in dataObject.Children
                                 select new ChildBusinessObject
                                 {
                                     Name = c.Name
                                     // etc.
                                 }
                GrandChildren = from c in dataObject.Children
                                from gc in c.Children
                                select new ChildBusinessObject
                                {
                                    Name = c.Name
                                    // etc.
                                },
                // etc.
            };