这是我获取第一篇书评的重复器:
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSource='<%# Eval("Reviews") %>' ItemType="ELibraryModel.Review">
<ItemTemplate>
<div class="new_prod_box">
<div class="new_prod_bg">
<asp:HyperLink ID="HyperLink1" CssClass="thumb" runat="server" ImageUrl='<%# String.Format("../Images/books/{0}.jpg", Item.Id.ToString()) %>' Text='<%# Item.Title %>' NavigateUrl='<%# "../books/bookdetails.aspx?reviewId=" + Item.Id.ToString() %>'></asp:HyperLink>
<a><asp:Label ID="DescriptionLabel" runat="server" Text='<%# Item.Title %>' /></a>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
在代码后面,我使用这样的东西来获得第一次审查,它工作:
using (ELibraryEntities entities = new ELibraryEntities())
{
var firstBook = (from books in entities.Books.Include("Reviews")
orderby books.Category
select new { books.Reviews }).Take(1);
Repeater2.DataSource = firstBook;
Repeater2.DataBind();
}
如何根据评论Id获得我想要的评论。
我正在尝试这样做:
using (ELibraryEntities entities = new ELibraryEntities())
{
var review = (from books in entities.Books.Include("Reviews")
where books.Id == 13
orderby books.Category
select new { books.Reviews }).Single();
Repeater2.DataSource = review;
Repeater2.DataBind();
}
但它不起作用。问题是我无法访问Reviews表的Id。books.Id == 13
属于Books表
我需要改变后面和中继器的代码吗?
谢谢。
试试这个:
using (ELibraryEntities entities = new ELibraryEntities())
{
var review = (from review in entities.Reviews
where review.BookId == BookId
select review).FirstOrDefault();
Repeater2.DataSource = review;
Repeater2.DataBind();
}
使用上面的代码片段,您可以从评论中获得第一篇评论,该评论是为Id等于给定的书BookId
编写的。
注释:如果本书至少有一个评论,您将获得第一个评论。否则,查询结果将为空。
有关FirstOrDefault方法如何工作的更多说明,请查看此处