Entity Framework mapping to DTO too slow

2.1k views Asked by At

Entity Framework is building a SQL query that takes less than 2 seconds. Even though the query is ugly, it's fast. In the EF SELECT statementI'm building a DTO based on my entites. The DTO has around 20 properties and it's plain. So, EF is running a query that returns these 20 properties I need. Everything seems fine but building the DTO takes almost 10 seconds. I have already told EF not to track changes (AsNoTracking() over the db sets) so I'm not sure what's happening between the query is executed and the DTO is built.

What's EF doing under the hood that makes it so slow? Again, the query is fine and returns really fast but building the DTO with those properties is really slow.

I replaced this logic by a stored procedure that returns the same 20 properties and it is really, really fast. The DTO is the same so there has to be something in the middle, between reading the results of the query and building the DTO that is different.

I hope someone can help me figure out what's going on.

EDIT:

I'm adding how I'm populating the DTO based on a comment.

.Select(p => new PMPanelOffersDTO()
                                {
                                    OfferId = p.Id,
                                    OfferDate = p.DateCreated,
                                    UserId = p.UserId,
                                    OfferAmountId = p.AmountId,
                                    OfferAmountTypeId = p.Amount != null ? p.Amount.OfferType.Id : default(int?),
                                    OfferAmountType = p.Amount != null ? p.Amount.OfferType.Name : null,
                                    TowerCompanyName = p.Amount != null && p.Amount.Tower != null ? p.Amount.Tower.CompanyName : null,

... { the same for the other properties }

2

There are 2 answers

1
yavuz On

Do you apply paging? (I mean skip&take) And most importantly where exactly ToList() is used? We have exactly the same problem, solved in a such a way that use ToList() after DTO construction.

1
hal9000 On

Try using .ToList() on the resulting object. That's all it took in our case. I agree it made no sense. Apparently the IEnumerable<> was not a happy thing