C# IQueryable<;评论>;GetComments:显示带有产品详细信息的注释

C# IQueryable<;评论>;GetComments:显示带有产品详细信息的注释,c#,asp.net,join,webforms,iqueryable,C#,Asp.net,Join,Webforms,Iqueryable,我正在创建一个web表单应用程序,允许用户查看产品列表,然后查看每个产品的详细信息。到目前为止,ProductDetails.aspx正在显示产品图像、说明和价格。我已经从我的产品表中创建了一个单独的表进行评论(评论表)。我想让用户能够在详细信息页面中登录并评论产品。我还希望所有这些评论在显示ProductDetails的任何时候都显示出来。下面是我的查询,以显示产品的详细信息,让您了解到目前为止它是如何编写的 public IQueryable<Product> GetProduc

我正在创建一个web表单应用程序,允许用户查看产品列表,然后查看每个产品的详细信息。到目前为止,ProductDetails.aspx正在显示产品图像、说明和价格。我已经从我的产品表中创建了一个单独的表进行评论(评论表)。我想让用户能够在详细信息页面中登录并评论产品。我还希望所有这些评论在显示ProductDetails的任何时候都显示出来。下面是我的查询,以显示产品的详细信息,让您了解到目前为止它是如何编写的

public IQueryable<Product> GetProduct([QueryString("productID")] int? productId)
    {
        var _db = new Critic.Models.ProductContext();
        IQueryable<Product> query = _db.Products;

        if (productId.HasValue && productId > 0)
        {
            query = query.Where(p => p.ProductID == productId);
        }
        else
        {
            query = null;
        }
        return query;
    }
public IQueryable GetProduct([QueryString(“productID”)]int?productID)
{
var_db=new Critic.Models.ProductContext();
IQueryable查询=_db.Products;
if(productId.HasValue&&productId>0)
{
query=query.Where(p=>p.ProductID==ProductID);
}
其他的
{
query=null;
}
返回查询;
}
我想将IQueryable与Comments一起使用,创建一个GetComments方法,在该方法中,我可以通过两个表对应的键连接它们。我不知道该怎么做。如果有人能给我举一些例子,说明如何让我上路,我将不胜感激

public IQueryable<Comments> GetComments([QueryString("commentID")] int? commentId)
{
}
public IQueryable GetComments([QueryString(“commentID”)]int?commentID)
{
}

您可以通过向数据库发出一个请求来实现这一点,而不是单独获取注释。你需要处理的唯一一件事是,因为你需要将你的产品和它的评论连接在一起,你可能会在.aspx页面上的每个评论都有一个重复的产品,然后你只需要在你的页面上显示一次所选的产品并循环其余的评论

public IQueryable GetProductDetails([QueryString(“productID”)]int?productID)
{
if(productId.HasValue&&productId>0)
{
使用(var context=new Critic.Models.ProductContext()){
var product=来自context.Products中的p
在context.ProductComments p.ProductId等于pc.ProductId中加入pc
其中p.ProductId==ProductId
选择新产品{
ProductId=p.ProductId,
CommentId=c.CommentId,
ProductName=p.ProductName,
CommentDesc=c.CommentDesc
};
退货产品;
}
}
其他的
返回null;
}

希望它能给你一个线索。

为什么OP需要一个联接表?连接表用于M:M关系,这对很多人来说(在产品方面)似乎是一个经典的1(在评论方面)?感谢@JimMSDN提到它,上面的代码中有一个额外的连接,我已经更新了它。剩下的联接只用于product表中剩余的产品详细信息,因此它不仅用于注释,否则使用ProductId获取注释就足够了。
public IQueryable<Product> GetProductDetails([QueryString("productID")] int? productId)
{
    if (productId.HasValue && productId > 0)
    {
       using (var context = new Critic.Models.ProductContext()){
          var product= from p in context.Products
              join pc in context.ProductComments p.ProductId equals pc.ProductId
              where p.ProductId == productId
              select new Product { 
                       ProductId = p.ProductId, 
                       CommentId = c.CommentId,
                       ProductName = p.ProductName, 
                       CommentDesc = c.CommentDesc
                     };
           return product;
       }
    }
    else
        return null;
}