将数据从多个数据库表检索到ASP.NET Core中的API

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

我在SQL Server中有一个数据库,本地存储有许多不同的表,它们通过不同类型的关系(一对多和多对多)连接在一起。您可以看到一些这样的主题:

enter image description here

[我在VS 2019上使用Entity Framework为此创建了一个Web API。

我使用脚手架来创建控制器,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OneClickAPI.Models;

namespace OneClickAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("enableCors")]
    public class ProductsController : ControllerBase
    {
        private readonly OneClickDBContext _context;

        public ProductsController(OneClickDBContext context)
        {
            _context = context;
        }

        // GET: api/Products
        [HttpGet]
        public IEnumerable<ProductsTbl> GetProductsTbl()
        {
            return _context.ProductsTbl;
        }

        // GET: api/Products/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetProductsTbl([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var productsTbl = await _context.ProductsTbl.FindAsync(id);

            if (productsTbl == null)
            {
                return NotFound();
            }

            return Ok(productsTbl);
        }

        // PUT: api/Products/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutProductsTbl([FromRoute] int id, [FromBody] ProductsTbl productsTbl)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != productsTbl.Id)
            {
                return BadRequest();
            }

            _context.Entry(productsTbl).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductsTblExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Products
        [HttpPost]
        public async Task<IActionResult> PostProductsTbl([FromBody] ProductsTbl productsTbl)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.ProductsTbl.Add(productsTbl);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetProductsTbl", new { id = productsTbl.Id }, productsTbl);
        }

        // DELETE: api/Products/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProductsTbl([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var productsTbl = await _context.ProductsTbl.FindAsync(id);
            if (productsTbl == null)
            {
                return NotFound();
            }

            _context.ProductsTbl.Remove(productsTbl);
            await _context.SaveChangesAsync();

            return Ok(productsTbl);
        }

        private bool ProductsTblExists(int id)
        {
            return _context.ProductsTbl.Any(e => e.Id == id);
        }
    }
}

我的模型看起来像:

namespace OneClickAPI.Models
{
    public partial class ProductsTbl
    {
        public ProductsTbl()
        {
            BuyBillDetalisTbl = new HashSet<BuyBillDetalisTbl>();
            ItemMovmentTbl = new HashSet<ItemMovmentTbl>();
            ItemStoresTbl = new HashSet<ItemStoresTbl>();
            SaleBillDetialsTbl = new HashSet<SaleBillDetialsTbl>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public int? Qty { get; set; }
        public decimal? BuyPrice { get; set; }
        public decimal? SalePice { get; set; }
        public decimal? SaleGomla { get; set; }
        public decimal? AvgCost { get; set; }
        public int? QtyLimite { get; set; }
        public decimal? SaleLimite { get; set; }
        public int? CatId { get; set; }
        public int? BranchId { get; set; }

        public BranchTbl Branch { get; set; }
        public CatTbl Cat { get; set; }
        public ICollection<BuyBillDetalisTbl> BuyBillDetalisTbl { get; set; }
        public ICollection<ItemMovmentTbl> ItemMovmentTbl { get; set; }
        public ICollection<ItemStoresTbl> ItemStoresTbl { get; set; }
        public ICollection<SaleBillDetialsTbl> SaleBillDetialsTbl { get; set; }
    }
}

但是问题是我的API无法从连接的表中获取数据

[
{
"id": 1002,
"name": "item 1",
"qty": 30,
"buyPrice": 22,
"salePice": 27,
"saleGomla": 25,
"avgCost": 22,
"qtyLimite": 5,
"saleLimite": 22,
"catId": 1,
"branchId": null,
"branch": null,
"cat": null,
"buyBillDetalisTbl": [],
"itemMovmentTbl": [],
"itemStoresTbl": [],
"saleBillDetialsTbl": []
},
{
"id": 1017,
"name": "item 2",
"qty": 20,
"buyPrice": 15,
"salePice": 20,
"saleGomla": 17,
"avgCost": 15,
"qtyLimite": 5,
"saleLimite": 16,
"catId": 2,
"branchId": null,
"branch": null,
"cat": null,
"buyBillDetalisTbl": [],
"itemMovmentTbl": [],
"itemStoresTbl": [],
"saleBillDetialsTbl": []
}
]

因此,如何使用Entity Framework将这些表联接成为API,以从连接的表中获取所有数据?

更新:

例外

        }
        // GET: api/Products
        [HttpGet]
        public IEnumerable<ProductsTbl> GetProductsTbl()
        {
            var products = _context.ProductsTbl // this line in red
              .Include(p => p.BranchId)
              .Include(p => p.Cat)
              .Include(p => p.BuyBillDetalisTbl)
              .ToList();
            return _context.ProductsTbl;
        }
lambda_method(Closure , object , object[] )
c# sql-server api asp.net-core entity-framework-core
1个回答
1
投票

您可以使用Include从其他相关表中加载数据。例如:

var products = _context.ProductsTbl
              .Include(p => p.branchTbl)
              .Include(p => p.catTbl)
              .ToList();

请检查Loading Related Data,这说明了加载相关表数据的不同方法。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.