Blog

Filter posts by Category Or Tag of the Blog section!

Why you can't project mapped entity in entity framework

Saturday, 24 May 2014

If you have worked with entity framework for a long time with and LINQ of course, you probably have seen the Error: The entity cannot be constructed in a LINQ to Entities query. So when it happens and why? Think about the following piece of code:

public IQueryable<Lesson> GetAllLessons(int termId)

{

    return from p in db.Lessons

           where p.termId == termId

           select new Lesson{ Name = p.Name};

}

Note: a Lesson is an Object that has been mapped via the entity framework

Now if you run the code you will see the error we talked about, you should use DTO objects instead of the mapped object:

public IQueryable<LessonDTO> GetAllLessons(int termId)

{

    return from p in db.Lessons

           where p.termId == termId

           select new LessonDTO { Name = p.Name};

}

So what’s happening in the back? As you know the mapped entities in EF represent database tables. If you project onto a mapped entity, you partially load an entity, which is not a valid state. Entity Framework won't have any clue how to handle an update of the entity. So if EF would project the mapped object, you would risk losing some of your data in the Database, therefore it is not allowed to partially load entities.

comments powered by Disqus