Entity framework core 如何在ASP.NET Core API控制器中获取多个表的记录
我想从数据库中获取3个表,仅获取3个表中的所有值 这个api位于Sales Controller中,我想在其中获取3个表Customer、Product和Store,以便在表单中使用它们 下面是数据库上下文Entity framework core 如何在ASP.NET Core API控制器中获取多个表的记录,entity-framework-core,asp.net-core-2.0,asp.net-apicontroller,Entity Framework Core,Asp.net Core 2.0,Asp.net Apicontroller,我想从数据库中获取3个表,仅获取3个表中的所有值 这个api位于Sales Controller中,我想在其中获取3个表Customer、Product和Store,以便在表单中使用它们 下面是数据库上下文 namespace CRUDReact.Model { public class DataBaseContext: DbContext { public DataBaseContext(DbContextOptions<DataBaseContext> options)
namespace CRUDReact.Model
{
public class DataBaseContext: DbContext
{
public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options) { }
public DbSet<Customer> Customer { get; set; }
public DbSet<Sales> Sales { get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<Store> Store { get; set; }
}
}
使用Include获取Sales将导致从子表获取数据。你为什么要投射它
var salesdata = await _context.Sales
.Include(s => s.Customer)
.Include(s => s.Product)
.Include(s => s.Store).ToListAsync();
此外,通常销售会有商店,客户和产品清单,你确定你的型号是正确的
namespace CRUDReact.Models
{
public class Sales
{
[Key]
public int SalesId { get; set; }
public int ProductRefId { get; set; }
[ForeignKey("ProductRefId")]
public Product Product { get; set; }
public int CustomerRefId { get; set; }
[ForeignKey("CustomerRefId")]
public Customer Customer { get; set; }
public int StoreRefId { get; set; }
[ForeignKey("StoreRefId")]
public Store Store { get; set; }
[DataType(DataType.Date)]
public string DateSold { get; set; }
}
}
var salesdata = await _context.Sales
.Include(s => s.Customer)
.Include(s => s.Product)
.Include(s => s.Store).ToListAsync();