Ehsan Ghanbari

Experience, DotNet, Solutions

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 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.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I'm spending a lot of my time on software architecture. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus