我有这个型号
(宠物)Mascota.cs
namespace BE_CRUDMascotas.Models
{
public class Mascota
{
public int Id { get; set; }
public string Raza { get; set; }
public string Nombre { get; set; }
public string Color { get; set; }
public int Edad { get; set; }
public float Peso { get; set; }
public int DueñoId { get; set; }
public Dueño Dueño { get; set; }
public DateTime FechaCreacion { get; set; }
}
}
(所有者)Dueño.cs
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace BE_CRUDMascotas.Models
{
public class Dueño
{
public int Id { get; set; }
public string Cedula { get; set; }
public string Nombres { get; set; }
public string Apellidos { get; set; }
public DateTime FechaCreacion { get; set; }
public virtual List<Mascota> Mascotas { get; set; } = null!;
}
}
这是 DueñoController.cs 中用于创建所有者的 post 方法
[HttpPost]
public async Task<ActionResult> Post(Dueño dueño)
{
try
{
dueño.FechaCreacion = DateTime.Now;
_context.Dueños.Add(dueño);
await _context.SaveChangesAsync();
return CreatedAtAction("Get", new { id = dueño.Id }, dueño);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
原因是主人有很多宠物,但一只宠物只是一个主人。
问题是,您需要首先创建一个所有者才能创建可以链接到所有者的宠物,当我运行 swagger 时,我尝试将“List Mascotas”字段留空,但它说这是必需的,即使我使用“= null!”在现场,我也尝试过使用“[BindNever]”,但它不起作用。
是否可以将该字段留空或者我需要删除该字段?
我使用的是网6
如果您想让该字段为空,请尝试添加
?
:
public virtual List<Mascota>? Mascotas { get; set; }
首先将声明更改为默认实现,这使得序列化器能够为数组中的每个项目调用
.Add()
:
public virtual List<Mascota> Mascotas { get; set; } = new HashSet<Mascota>();
我知道您试图不添加宠物,这通常足以让验证者做他们的事情。
它是从 Postman 失败还是只是在 swagger UI 中失败?
请注意,您也可以在初始帖子中包含子宠物记录,它不必单独发布到其他控制器。