【问题标题】:Lookup using Entity Framework使用实体框架查找
【发布时间】:2018-04-15 20:21:39
【问题描述】:

我正在尝试使用 Entity Framework 跨 2 个表进行查找,不幸的是我找不到方法,但我确实有 sql 查询可以满足我的需求

SQL 查询

select top(1) p1.Percentage
from LookupTable p1 , [lookupTablePerUnit] p2
where p2.[LookupValue] <= @Value1  and p1.ID=p2.[LookupID]
order BY pr.range DESC

如果@Value1= 6,那么结果 = 52

这是使用此查询的两个表 (lookupTable && LookTablePerUnit) 的屏幕截图

(SELECT * FROM [DB].[dbo].[lookupTablePerUnit] p1 , [DB].[dbo].[LookupTable] p2
where p1.LookupTableID = p2.ID)

http://s15.postimage.org/m80zvn4mx/Captur2e.png

【问题讨论】:

标签: c# entity-framework linq entity-framework-4


【解决方案1】:

连接(您的查询使用 SQL 的隐式连接语法)在 Linq to Entities 中看起来非常相似:

var query = from p1 in context.LookupTable 
            join p2 in context.lookupTablePerUnit on p1.ID equals p2.LookupID
            where p2.LookupValue <= Value1
            orderby p1.range descending
            select p1.Percentage;

var result = query.FirstOrDefault();

不得不猜测range 属性,您的问题中有错字,因此不清楚它是否可以归因于LookupTablelookupTablePerUnit

【讨论】:

    【解决方案2】:

    类似这样的东西(希望你使用的是 C#):

    int value1 = 6;
    int percentage = (from p1 in context.LookupTable
                     from p2 in context.lookupTablePerUnit
                     where p2.LookupValue <= value1 and p1.ID=p2.LookupID
                     orderby p2.range descending
                     select p1.Percentage).First();
    

    context 是您的 ObjectContext 实例。请注意,Entity Framework 可能会错误地将您的实体名称复数,因此 LookupTableLookupTablePerUnit 实际上可能类似于 ObjectContext 中的 LookupTableslookupTablePerUnits(并且 lookupTablePerUnit 可能大写)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      相关资源
      最近更新 更多