You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求.NET Core中Buyer与RicePrice表乘算API控制器的Get/Post代码

先修正实体类的错误

你的Buyer实体类中外键属性标注有误,[ForeignKey("RiceId")]不应该加在Outputt字段上,应该移到RicePrice导航属性上;另外建议初始化RicePrice的集合属性避免空引用,修正后的实体类如下:

public class Buyer
{
    [Key]
    public int Id { get; set; }
    public int Quantity { get; set; }
    public int RiceId { get; set; }
    [ForeignKey("RiceId")]
    public RicePrice RicePrice { get; set; }
    public int Outputt { get; set; } // 仅存储计算结果,无需外键标记
}

public class RicePrice
{
    [Key]
    public int Id { get; set; }
    public int Price { get; set; }
    public ICollection<Buyer> Buyers { get; set; } = new List<Buyer>();
}
控制器的Get/Post方法实现

假设你已经配置了名为AppDbContext的数据库上下文,以下是完整的控制器代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[Route("api/[controller]")]
[ApiController]
public class BuyersController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public BuyersController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    // GET: api/Buyers
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Buyer>>> GetAllBuyers()
    {
        // 关联查询RicePrice数据,返回完整的关联信息
        return await _dbContext.Buyers.Include(b => b.RicePrice).ToListAsync();
    }

    // GET: api/Buyers/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Buyer>> GetBuyerById(int id)
    {
        var buyer = await _dbContext.Buyers.Include(b => b.RicePrice)
                                           .FirstOrDefaultAsync(b => b.Id == id);

        if (buyer == null)
        {
            return NotFound("未找到指定的采购记录");
        }

        return buyer;
    }

    // POST: api/Buyers
    [HttpPost]
    public async Task<ActionResult<Buyer>> CreateBuyer(BuyerCreateRequest request)
    {
        // 验证对应的大米价格记录是否存在
        var ricePrice = await _dbContext.RicePrices.FindAsync(request.RiceId);
        if (ricePrice == null)
        {
            return BadRequest($"不存在ID为{request.RiceId}的大米价格记录");
        }

        // 计算Outputt值
        int calculatedOutput = request.Quantity * ricePrice.Price;

        // 构建Buyer实体
        var buyer = new Buyer
        {
            Quantity = request.Quantity,
            RiceId = request.RiceId,
            Outputt = calculatedOutput
        };

        _dbContext.Buyers.Add(buyer);
        await _dbContext.SaveChangesAsync();

        // 返回包含关联数据的创建结果
        return CreatedAtAction(nameof(GetBuyerById), 
                               new { id = buyer.Id }, 
                               await _dbContext.Buyers.Include(b => b.RicePrice)
                                                      .FirstOrDefaultAsync(b => b.Id == buyer.Id));
    }
}

// 定义Post请求的接收DTO,避免直接暴露实体类的冗余字段
public class BuyerCreateRequest
{
    public int Quantity { get; set; }
    public int RiceId { get; set; }
}
核心逻辑说明
  • 使用BuyerCreateRequest作为Post请求的接收对象,防止前端传入不必要的字段(如Id、Outputt),保证数据安全。
  • Post方法中先校验RiceId对应的价格记录是否存在,避免无效数据入库。
  • 直接从数据库获取最新的Price值进行计算,确保结果准确。
  • Get方法通过Include实现关联查询,返回包含大米价格信息的完整采购记录。

内容的提问来源于stack exchange,提问作者Karthick1211

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:40:14