我正在使用 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/