【问题标题】:Getting multiple tables with single db call in entity framework在实体框架中使用单个数据库调用获取多个表
【发布时间】:2013-06-12 10:09:28
【问题描述】:

我是 ASP.NET MVC 和实体框架的新手。以前我曾经使用 ADO.NET 数据表和数据集。因此,在单次调用从数据库中获取多个表的场景中,我曾经使用 DataSet。例如

ALTER PROCEDURE [dbo].[SpTest]
As
Begin

    Select * from Table1
    Select * from Table2

End

在 C# 上,我曾经这样做

Dataset ds = DAL.GetDataSetBySp("SpTest");
Datatable dt1 = ds.Tables["Table1"];
Datatable dt2 = ds.Tables["Table2"];

现在如果我想在 Single Db Call 中使用 Entity Framework 的多个表,我该怎么做?

【问题讨论】:

  • 答案很简单:你不能。在 EF 中没有什么比 NHibernate 的多查询更好的了。但是我可以问你需要什么吗?也许您的问题可以通过不同的方式解决。
  • 在我的应用程序中,我的主页上有一个仪表板。这实际上是整个应用程序的摘要。数据来自不同的表。有些表是相互关联的,有些表是不相互关联的。我遇到的问题是那些彼此没有任何关系的表。
  • 如果您可以将每个表的数据压缩到相同的行结构中,那么您可以获得的最接近的是使用Union
  • 我试图这样做,但不幸的是这不是一个选择。 :(
  • 我想现在我必须进行多个数据库调用并在 ViewModel 中设置数据,然后将其传递给 View。

标签: asp.net sql-server asp.net-mvc entity-framework database-optimization


【解决方案1】:

你可以这样做,但表中应该有关系:

public class Table1
{
 [Key]
 public int IDCol{ get; set; }
 public string Col2{ get; set; }
}

public class Table2
{
 [Key]
 public int IDCol2{ get; set; }
 public int IDCol{ get; set; }
 public string Col3{ get; set; }
}

public class JoiningTable
{
  public int IDCol1{ get; set; }
  public int IDCol2{ get; set; }
  public string Col2 { get; set; }
  public string Col3 { get; set; }
}

public List<JoiningTable> GetData()
{
 List<JoiningTable> bothTablesData =
      from t in Table1
      join t2 in Table2
      on t.IDCol equals t2.IDCol1 
      select new { IDCol1 = t.IDCol, Col3 = t2.Col3, Col2 = t.Col2 }.ToList<JoiningTable>();

  return bothTablesData;
}

【讨论】:

  • 如果两个表之间存在关系,则完全没有问题。即使您不必创建联接表。我问的是没有关系的表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2018-01-02
  • 1970-01-01
相关资源
最近更新 更多