【问题标题】:Linq & Entityframework, ISNull and getting a single value from a joinLinq & Entityframework,ISNull 并从连接中获取单个值
【发布时间】:2013-02-11 03:57:41
【问题描述】:

我正在尝试在 linq 中复制以下 SQL 查询:

Select
     l.*,
    ISNULL( i.InterestPercentage,0)
     as InterestPercentage
FROM properties l
LEFT JOIN interest i on i.ListingKey = l.ListingKey
Where i.userId = {0}

我现在真的没什么可做的:

var results = from l in context.properties
              join s in context.interest on l.ListingKey equals s.ListingKey
              where s.userId == "";

这会返回一个完整的连接,但我想返回带有单个附加值的属性,即InterestPercentage。我想我可能需要创建一个新对象,它是所有属性列以及一个额外的 InterestPercentage 属性。然后添加select new MyObject { tons of property setters }

此外,我正试图通过 Odata 公开这一点,这样做是否会失去可查询的能力?

【问题讨论】:

    标签: linq odata entity-framework-4.3


    【解决方案1】:

    你可以尝试返回

    new {MainObj = l, InterestPercentage = (your calculated field)}
    

    或者创建一个与上述结构相似的对象。这将帮助您避免所有属性设置。

    【讨论】:

    • 最终这样做了。谢谢
    【解决方案2】:

    当您通过 OData 公开此查询时,您必须重写它以不使用联接。 OData 不支持连接,但支持扩展,即在单个请求中获取相关集合。为了能够扩展您的 OData 查询,您需要在元数据中定义相应的关系,即,如果您想使用 ListingKey 作为连接字段从 Properties 和 Interest 获取数据,您将需要基于这些表之间的关系在ListingKey(或引用这两个的另一个表)上。

    【讨论】:

      【解决方案3】:

      您没有使用join,您可以通过创建自己的显式连接来模拟连接:

      var results = from prp in context.properties
                    from inr in context.interest // cross join
      
                    // your own join phrase
                    where inr.ListingKey == (prp.InterestPercentage ?? 0)
                          && inr.userId == ""
                    select new { ... };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-11
        相关资源
        最近更新 更多