使用子查询帮助linq查询

时间:2009-10-28 13:00:46

标签: c# sql linq linq-to-sql lambda

任何人都可以帮忙吗?我坚持使用linq查询..

基本上我有一个标准的linq查询返回字段,1个字段(保险)实际上是另一个linq查询,如此

   // original from this in etc not included to keep msg short>
    select new Models.Custom.House.Insurance()
               {
                   Id = v.IdHouse,
                   Insurances = from gt in GroupHouseTariffs
                                join  i in InsuranceGroup
                                    on new { gt.IdTariff, gt.IdGroup}
                                       equals
                                       new { i.IdTariff, i.IdGroup}
                                select new
                                       {
                                           InsuranceId = i.Id,
                                           Price = i.Price
                                       }

基本上保险是从Models.Custom.House注入保险财产,它可以工作,因为我可以在我的调试中看到它...我在保险中有4条记录..保险是这样定义在房子里基本上另一个小班的Iqueryable ..

       public IQueryable<Insurance> Insurances { get; set;}

所以我试着写一个扩展方法,就像这样

    public static IQueryable<House> WithInsuranceId(this IQueryable<House> qry, int insuranceId)
    {
        return from h in qry
               where h.Insurance .. // BUT here is the problem i don't see my properties, I see plenty of linq methods

    }

我应该能够看到insuranceId并执行此操作,不是吗?

    return from h in qry
               where h.Insurance.InsuranceId == 1;

这是班级(非常小)

    public class Insurance
    {
        public int? InsuranceId { get; set; }
        public float? price{ get; set; }
    }

也许我需要了解一些特殊的lambda :-)?

任何帮助都非常感谢,谢谢。

1 个答案:

答案 0 :(得分:2)

您发布的样本中是否存在拼写错误?

我注意到以下内容:

// No object name specified, Price has a capital P
select new
{
    InsuranceId = i.Id,
    Price = i.Price
}

// Price has a small p
public class Insurance
{
    public int? InsuranceId { get; set; }
    public float? price{ get; set; }
}

现在,您的实际查询对我来说也是错误的。

House.Insurance有一个名为ID的属性和一个名为Insurances的属性,这是一个集合。然而,您的查询指出:

 return from h in qry
           where h.Insurance.InsuranceId == 1;

你的意思是:

return from h in qry
           where h.Insurance.Id == 1 select h;

或者:

return from h in qry
           where h.Insurance.Insurances.Contains(i => i.InsuranceID ==1) select h;
相关问题