为什么我的 Linq 语句被执行两次?
我正在开发内部消息系统。我连接了 mvc 迷你分析器,它向我显示一些语句被执行了两次,我不明白为什么,
我的控制器就像你能得到的一样简单:
var db = MessagingDataContext.Get();
return db.Posts.OrderByDescending(p => p.DatePosted).Skip(pagenumber * pagesize).Take(pagesize);
而且我的视图也一样简单(我的 _Layout 页面具有其余的标记):
@foreach (var post in Model)
{
<div class="post">
<p>
@Html.ActionLink(post.Title, "View", "Posts", new { postid = post.Id}) by @post.User.Name
</p>
</div>
}
那么为什么 get_User 会被执行两次?
I am working on an internal message system. I have the mvc mini profiler hooked up, and it is showing me some statements are executed twice, and I can't figure out why,
My controller is as simple as you can get:
var db = MessagingDataContext.Get();
return db.Posts.OrderByDescending(p => p.DatePosted).Skip(pagenumber * pagesize).Take(pagesize);
and my view is just as simple (my _Layout page has the rest of the markup):
@foreach (var post in Model)
{
<div class="post">
<p>
@Html.ActionLink(post.Title, "View", "Posts", new { postid = post.Id}) by @post.User.Name
</p>
</div>
}
So why would get_User be executed twice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该查询正在获取每个用户的用户名。参数@p0是用户ID。如果您检查它的值,您很可能会发现每个查询的值都不同。
The query is fetching the username for each user. The parameter @p0 is the user ID. If you check the value of it, you will most likely find that it is different for each query.
Linq 语句不会执行两次。第一个查询来自 Linq 语句,我猜测第二个和第三个查询来自您的 @foreach 循环。
The Linq statement is not being executed twice. The first query is from the Linq statement, and I am guessing the 2nd and 3rd queries are from your @foreach loop.
我的猜测是因为
@post.User.Name
部分正在为每条记录执行。原来的查询返回2个结果吗?解决此问题的最佳方法是在原始查询中执行选择以获取所需的所有信息(标题、ID 和用户名)。
My guess is because the
@post.User.Name
part is executing for each record. Did the original query return 2 results?Best way to fix this is in the original query do a select to get all the info you want (Title, ID and Username).