entity-framework - 使用Entity Framework core从多个相关表中获取数据并在Asp.Net Core中的 View 中显示

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

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

最佳答案

要完成这些步骤,您需要 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.

如果您需要学习如何建立关系,以下网站提供了有关 Entity Framework 的非常好的文档和演练。

我希望以下链接有所帮助:

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

关于entity-framework - 使用Entity Framework core从多个相关表中获取数据并在Asp.Net Core中的 View 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43627426/

相关文章:

c# - 在运行时更改 DbContext 连接

c# - 获取导航属性的 Count() 而无需在 Entity Framework 中加载整个集合

c# - 为什么 EF 在进行一对多连接时会不必要地检索 ID?

c# - VS 2017 ASP.NET Core 测试项目 - Microsoft.AspNetCore.Identity 缺失

c# - .Net 核心 2.2 未将 302 的状态代码更新为 401。OnRedirectToLogin 事件未触发

c# - 使用 EF 6 和 Oracle.ManagedDataAccess 时表不存在

angular - 在 ASP.NET Core 2.1 SPA 模板中找不到 webpack.config.js 或 webpack.config.vendor.js

asp.net-core - 是否可以根据 ASP.NET Core (Swashbucle) 中的响应 HTTP 代码设置响应 Content-Type?

c# - ASP.NET Core JWT/Windows 身份验证 HTTP 400 错误

asp.net-core - ASP.NET Core 中的基本身份验证