【问题标题】:Help with linq query with subqueries使用子查询帮助 linq 查询
【发布时间】:2009-10-28 13:00:46
【问题描述】:

任何人都可以帮忙吗?我被一个 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 条记录.. 保险在 House 中是这样定义的,基本上是另一个小类的 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 :-)?

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

【问题讨论】:

  • 如果你真的说where h.Insurance.InsuranceId == 1;,你会得到什么编译时错误?
  • 实际上在编译器之前我看到它是红色的但是如果我编译我得到'System.Linq.IQueryable'不包含'InsuranceId'的定义并且没有可以找到接受“System.Linq.IQueryable”类型的第一个参数的扩展方法“InsuranceId”

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


【解决方案1】:

您发布的示例中是否存在拼写错误?

我注意到以下几点:

// 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;

【讨论】:

  • 是的错别字:-) 哎呀......但就是这样! .. 包含 .. 很好用,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多