如何在ASP.NET Core API控制器中获取多个表的记录

问题描述 投票:0回答:1

我只想从数据库中提取3个表中的所有值。

此api在Sales Controller中,我想在其中获取3个表Customer,Product和Store,以便可以在表单中使用它。

这里是数据库上下文

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; }

}
}

这里是我要用来获取3个表的api。此api位于Sales Controller中。

   // GET: api/AllSales
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Object>>> GetAllSales()
    {
        var salesdata = await _context.Sales
                 .Include(s => s.Customer)
                 .Include(s => s.Product)
                 .Include(s => s.Store)
                 .Select(s => new
                 {
                     salesId = s.SalesId,
                     dateSold = s.DateSold,
                     customer = new
                     {
                         customerId = s.CustomerRefId,
                         name = s.Customer.Name,
                         address = s.Customer.Address
                     },
                     product = new
                     {
                         productId = s.ProductRefId,
                         name = s.Product.Name,
                         price = s.Product.Price
                     },
                     store = new
                     {
                         storeId = s.StoreRefId,
                         name = s.Store.Name,
                         address = s.Store.Address
                     }
                 })
                 .ToListAsync();
        return salesdata;
    }

这里是销售班

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; }
}
}
entity-framework-core asp.net-core-2.0 asp.net-apicontroller
1个回答
0
投票

[通过包含获取销售信息将导致从子表中获取数据。你为什么要投影它。

var salesdata = await _context.Sales
             .Include(s => s.Customer)
             .Include(s => s.Product)
             .Include(s => s.Store).ToListAsync();

通常,“销售”将具有商店,客户和产品清单,您确定您的型号正确吗。

© www.soinside.com 2019 - 2024. All rights reserved.