Linq数据来自两个具有聚合函数的表

时间:2015-07-17 07:02:46

标签: c# linq

我有两张桌子(产品和评论)

产品

ProductId
ProductName
ImagePath
CategoryID

查看

ReviewId
ProductId
ReviewText

我想要一个结果集,显示产品的productName,ImagePath和总评论。

我为此写了一个SQL查询

select ProductName, ImagePath,COUNT(rw.ProductId) TotalReview 
from Product pr join Review rw on pr.ProductId = rw.ProductId 
where pr.CategoryID=1
group by ProductName, ImagePath

请帮忙。

2 个答案:

答案 0 :(得分:1)

这是您查询的EF Linq代码

   var query = from p in db.Products
          where p.CategoryID = 1
          select new {
             Name = p.ProductName,
             ImagePath = p.ImagePath,
             TotalReviews = p.Reviews.Count()                
          };

    var results = query.ToList();

答案 1 :(得分:0)

您会喜欢使用Entity Framework执行此操作: 如果您还没有这样做,请将Entity Framework Nuget Package添加到您的项目中。

然后添加以下类:

[Table("Product")]
public class Product
{
    [Key]
    public int ProductId {get;set;}
    public string ProductName {get;set;}
    public string ImagePath {get;set;}

    [InverseProperty("Product")]
    public virtual ICollection<Review> Reviews {get;set;}
}

[Table("Review")
public class Review
{
    [Key]
    public int ReviewId {get;set;}
    public int ProductId {get;set;}
    public string ReviewText {get;set;}

    [ForeignKey("ProductId")]
    public virtual Product Product {get;set;}
}

public class YourDbContext : DbContext
{
    static YourDbContext()
    {
        //This prevents your database to be created or updated by EF
        //I prefer to keep the hand on my db
        Database.SetInitializer<YourDbContext>(null);
    }

    public YourDbContext()
        //The name value is the name of your connectionstring (in App.config or Web.config)
        //<configuration><connectionStrings><add ...
        : base("Name=YourDbContext"){}

    public DbSet<Product> Products {get;set;}
}

然后,您可以通过以下方式访问您的产品:

var dbContext = new YourDbContext();
var allProjects = dbContext.Projects;
var specificProject = dbContext.Projects.Where(p => p.ProductId == 5);

//Related Reviews will be availlable here
var specificReviews = specificProject.Reviews;

玩得开心!