在实体查询中基于ID检索关联元素

时间:2015-07-23 20:28:16

标签: asp.net-mvc linq entity-framework

我有一个实体查询,它将属性评论的数量分组到一个属性。但是我在查询中遇到一些问题,根据其propertyID拉取属性上的其余数据。谢谢!

示例结果:

|PropertyID | NumOfReviews |     StreetAddress     |    City    |
      1             14             1600 Speaker St.        Miami

查询:

var query1 = from r in db.Reviews
                    group r by r.propertyID into g
                    select new
                    {
                        propertyID = g.Key,
                        numofReviews = g.Count()
                        //Get Rest of data
                    };

物业模型:

 public partial class Property
{        
    public int propertyID { get; set; }
    public string streetaddress { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public string state { get; set; }
    public string country { get; set; }
    public string route { get; set; }

    public virtual ICollection<Review> Reviews { get; set; }
}

评论模型:

  public partial class Review
{
    public int reviewID { get; set; }
    public int propertyID { get; set; }
    public int rating { get; set; }
    public string review { get; set; }    
    public virtual Property Property { get; set; }
}

1 个答案:

答案 0 :(得分:1)

你能从相反的方向来看它吗?

var query = from p in db.Properties
            select new {
                propertyId = p.PropertyId,
                numofReviews = p.Reviews.Count()
                //Grab remaining properties off of the p variable that you need
            };