I have an SQL Server Express 2012 with the following event model in the Entity Framework:
eventPage: ID, name, description ..
eventDates: IDEvent, DateStart, DateEnd ..
eventTopics: IDEvent IDTopic ..
topics: ID, name, description..
So eventDates has an eventPage property and eventPage has an IEnumerable and eventTopic has a topic property and so on.
I want to make a query throuth the model and the result map it to my custom classes in C#.
I dont want to use the model classes generated by the EF, i have some classes with the only properties i need. ie:
Topic: ID, Name
EventDate: DateStart, DateEnd
Event: ID, Name, Topics, Start, End
Being Topics a List of Topic and Dates a List of EventDates
I have a method that makes the query and returns a IQueryable and from it i want a List.
So the way i get it is:
var events=GetEvents(start, end);
var eventsList = (from ev in events
select new {event = ev, eventPage = ev.eventPage,topics=ev.eventTopics)).ToList();
//Mapping
var map = (from ev in eventsList
select new Event(ev.event,ev.eventPage,ev.topics)).ToList();
And in the constructor i set the properties:
this.name=eventPage.Name;
this.start=event.Start;
this.end=event.End;
this.topics = topics.Select(t=>t.Topic).ToList();
But this is a bit slow for a large number of events, i would like to know if there is a more optimus way.
At the beginning the constructor only parameter was the event and inside i got the event.eventPage.Name , etc but it was too slow so i get the data i need first and after it i call the constructor.
AutoMapper is your friend in such situation.
I suggest you read the Getting Started guide. It’s pretty simple to understand and you’ll be able to map from your query to your custom DTOs really fast.
Here’s the full Wiki guide. See Lists and Arrays.
In your case it’d be something like this:
AutoMapperalso allows you to do something like this:It’s really powerful! Entity Framework for example let’s you lazy load related entities by default and so I think the examples above work out of the box with a single query to the database to get the root object.