Reputation: 2799
here is my code in Controller
var q = context.post;
return View(q);
in view
@model IEnumerable<post>
@{
Line1: var question = Model.FirstOrDefault(o => o.parent == null);
Line2: var answers = Model.Where(o => o.parent != null);
}
I've checked with sql-profiler , each line1 and line2 entity sends sql-command to database . is this really meaning and purpose of using ORM? or I do sth wrong ?
Upvotes: 3
Views: 164
Reputation: 364249
In your case yes. You passed set to context and you are executing queries on that set. I even expect that both queries pulled all posts from database and executed Linq query in memory of your application because of conversion to IEnumerable<post>
defined by your view. If you want to execute only single query to database you must pass loaded objects to your view by using for example:
var q = context.post.ToList();
But it would be better to create a new view model and execute two separate queries in your controller - view should be dump and it should not contain any additional logic:
var postModel = new PostViewModel {
Question = context.post.FirstOrDefault(o => o.parent == null),
Answers = cotnext.post.Where(o => o.parent != null).ToList()
};
return View(postModel);
Edit:
As I'm looking on those queries it should be even possible to execute them in one roundtrip to database using Concat
- something like:
var result = context.post.Where(o => o.parent != null)
.Concat(context.post.Where(o => o.parent == null)
.OrderBy(...).Take(1))
.ToList();
var postModel = new PostViewModel {
Question = result.FirstOrDefault(o => o.parent == null),
Answers = result.Where(o => o.parent != null).ToList()
};
It is not tested but you can give it a try.
Upvotes: 6