【问题标题】:Fetch data from multiple related tables using Entity Framework core and display in view in Asp.Net Core使用 Entity Framework 核心从多个相关表中获取数据并在 Asp.Net Core 中显示
【发布时间】:2017-09-23 10:58:00
【问题描述】:

我正在使用 Entity Framework Core 开发一个 Asp.Net Core 应用程序。该应用程序基本上是电子商务。我想使用主表产品从多个相互关联的表中获取特定产品的信息,然后我想将数据传递给视图。任何人都可以在这方面帮助我。我找不到任何完美的 Joins 解决方案并将相关数据传递给 View。

【问题讨论】:

标签: entity-framework asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-1.0


【解决方案1】:

要完成这些步骤,您需要 Visual Studio 2022。

基于当前文档:

public class OrderDetail
{
    public int OrderDetailID { get; set; }
    public int OrderID { get; set; }
    public int ProductID { get; set; }
    public int Quantity { get; set; }
    public Order Order { get; set; }
}

public class Order
{
    public int OrderID { get; set; }
    public int CustomerID { get; set; }
    public int EmployeeID { get; set; }
    public DateTime OrderDate { get; set; }
    public List<OrderDetail> OrderDetails { get; set; }
}

这是一个非常简单的模型,只包含两个类,Order 和 OrderDetail 具有一对多的关系。下一步是添加一个新的上下文类并确保继承自 DbContext

public class MyContext : DbContext
{
    public DbSet<OrderDetail> OrderDetails { get; set; }
    public DbSet<Order> Orders { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=StoreDB;");
    }
}

现在要使用模型中的迁移创建数据库,请安装以下软件包;

Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

安装这些包后,在包管理器控制台中运行以下命令。

Add-Migration Initial

此命令构建迁移以为您的模型创建初始表集。执行成功后,再运行以下命令。

Update-Database to apply the new migration to the database. This command creates the database before applying migrations.

如果您需要学习如何建立关系,以下网站有非常好的文档和实体框架演练。

希望以下链接对您有所帮助:

https://entityframeworkcore.com https://www.learnentityframeworkcore.com

【讨论】:

  • 感谢您提供解决方案,它可以帮助其他人。作为其 4 岁的问题,它已经实施。
  • @MohammedAltaf 我同意。实体框架已经走过了漫长的道路。通过约定优于配置,更容易专注于程序员正在开发的系统的业务模型......这样,我们可以满足项目交付时间表。
猜你喜欢
  • 2021-06-13
  • 2018-03-19
  • 2021-12-03
  • 2020-06-16
  • 2019-02-23
  • 1970-01-01
  • 2016-10-14
  • 2017-08-01
  • 1970-01-01
相关资源
最近更新 更多