1

I use ASP.MVC / EF in my project.

The domain model as below:

public class Post
{
     public int Id {get;set;}
     public string Abstract {get;set;}
     public string Content {get;set;}
}

and the view model is

public class PostListView
{
     public int Id {get;set;}
     public string Abstract {get;set;}
}

statemens in action to get model:

 db.Posts.Where(...).Select(p=>new PostListView
 {
       Id = p.Id,
       Abstract = p.Abstract
 });

When I check the SQL generated by Entity Framwork, the select statement includes all three columns. Is there some way to make EF generate more effective SQL statements that only select the fields needed by view model?

Thank you!

2
  • What are you passing to your Where? Commented Jul 18, 2011 at 7:59
  • @Ladislav, thank you. After reading your comment, I created a small project for testing, and find it can ignore columns not needed. but in my realy project, the select condition is much more complicated(not related to ignored columns), and make generated sql include all fields. when I have more time, I will check it deeply. Commented Jul 19, 2011 at 1:27

1 Answer 1

1

You can do like this

 var postQuery = from p in db.Posts
                                      select new { p.Id,p.Abstract};

And the enumerate collection

foreach (var p in postQuery  ){
// fill your view model here

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! However after test, I find using this way lower performace. I guess EF should fix this problem. I remember Linq To SQL can automatically map to object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.