I am working on one Asp.Net Core application using Entity Framework Core. That app is basically into E Commerce. I want to fetch information of particular product from multiple tables which are related to each other using the master table product, and then i want to pass the data to the View. Can anyone help me in this regard. I am unable to find any perfect solution of Joins and pass the related data to View.
-
No details. What is the problem? source code?Andrei Mihalciuc– Andrei Mihalciuc2017-04-26 10:47:57 +00:00Commented Apr 26, 2017 at 10:47
-
learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-appalessalessio– alessalessio2017-04-26 14:47:59 +00:00Commented Apr 26, 2017 at 14:47
1 Answer
To complete these steps you need Visual Studio 2022.
Based on current documentation:
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; }
}
It is a very simple model which contains only two classes, Order and OrderDetail has a one-to-many relationship. The next step is to add a new context class and make sure to inherit from the DbContext class
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;");
}
}
Now to create a database using migrations from your model, install the following packages;
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
Once these packages are installed, run the following command in Package Manager Console.
Add-Migration Initial
This command scaffold a migration to create the initial set of tables for your model. When it is executed successfully, then run the following command.
Update-Database to apply the new migration to the database. This command creates the database before applying migrations.
If you need to learn how to set up relationships the following websites have very good documentation and walkthrough on the entity framework.
I hope the following links help:
https://entityframeworkcore.com https://www.learnentityframeworkcore.com