Question

I need some help working with an IQueryable collection of data items and then selecting them into a new form.

The following method is called to get some data from a repository:

var data = this.repository.GetAllPersonalDetails();

I want to then convert each item in the collection to a business object which I do using the following:

var businessTypes = data.Select(dataType => new PersonalDetails
    {
        FirstName = dataType.FirstName
        ...etc.
    });

This works fine and all is well, but the business object is quite big and I would like to make use of an adapter function that maps a data object to a business object. However, if I use code similar to the following:

var businessTypes = data.Select(dataType => this.ConvertToBusinessObject(dataType));

Then the whole Queryable pipeline gets messed up and I get exceptions when the query is eventually executed.

Does anyone know if what I'm trying to do is possible? It would be great if it was as we use adapter functions to convert between objects in a number of places and I'd rather re-use them instead of having to do the full conversion inline.

Was it helpful?

Solution 2

Answering my own question, the guidance given in the answer to this question worked perfectly for me.

Converting IQueryable<T> object to another object?

OTHER TIPS

The thing is, there has to be defined mapping from repository objects to business objects somewhere. You can't get it working without this or using LINQ select as you do.

There are many different ORMs (object-relational mappers) that maps database objects to business objects, but even they have to generate some adapters. For instace, Entity Framework uses templates to generate mapping classes and hides them under a context type so you are not bothered with it.

If you don't want or can't use any existing mapper, you can write your own adapters. When you are talking about adapters, I assume that you already know how they could be done.

AutoMapper is what you are looking for.

AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top