Why you can't project mapped entity in entity framework

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 peace of code:

  1. public IQueryable<Lesson> GetAllLessons(int termId)
  2. {
  3.     return from p in db.Lessons
  4.            where p.termId == termId
  5.            select new Lesson{ Name = p.Name};
  6. }

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

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

  1. public IQueryable<LessonDTO> GetAllLessons(int termId)
  2. {
  3.     return from p in db.Lessons
  4.            where p.termId == termId
  5.            select new LessonDTO { Name = p.Name};
  6. }

So what’s happening in 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.


Tags: Entity Framework C#


comments powered by Disqus