【问题标题】:Select from multiple tables using Entity Framework使用实体框架从多个表中选择
【发布时间】:2015-01-06 11:23:52
【问题描述】:

我正在使用实体框架。我想从数据库中没有外键关系的多个表中选择数据,例如

select  
    tOut.columnId, wo.columnType, tIn.* 
from 
    TbaleA tIn,
    TableB tOut,
    TableC wo
where
    1 = 1
    and tIn.columnRefId = tOut.columnGuid
    and tOut.columnId = wo.columnId

实体框架中是否有任何解决方案?我尝试过使用包含语法,但它对我不起作用..

【问题讨论】:

  • 什么不起作用?请更具体。

标签: c# entity-framework


【解决方案1】:

如果使用查询语法,即使不存在外键关系,也可以连接表。 它会沿着这些方向发展:

var result = from tIn in yourDbContext.TableA
             join tOut in yourDbContext.TableB on tIn.columnRefId equals tOut.columnGuid
             join wo in yourDbContext.TableC on tOut.columnId equals wo.columnId
             select new { tOut.columnId, wo.columnType, TableA = tIn };

【讨论】:

  • 它会起作用,但恕我直言,这是 ORM 的“未充分利用”。设置导航属性似乎更像是模仿 SQL 语句的精神。
【解决方案2】:

这些链接上有 lambda 和查询语法的示例:

MSDN 101 LINQ Samples (mostly query syntax)

Nilzor's LINQ 101 Samples - Lambda Style

【讨论】:

    【解决方案3】:

    另一种解决方案是在您的类中使用/添加导航属性,例如:

    class TableA {
        Int32 Id {get; set;}
    
        //navigation property
        TableB b {get; set;}
    }
    

    并在查询中使用它们

    from a in yourDbContext.TableA
    select new { a.Id, a.b.columnType}
    

    当然,可能会有一些配置(代码或注释)来设置关系以使其适合数据库模式。但是您将只做一次,而不是每次查询。

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2013-01-25
      • 2013-11-01
      • 2010-10-29
      • 2021-05-25
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多