ASP.NET Core Web API接收含关联属性的ContactEntity时JSON转换报错求助
问题:ASP.NET Core Web API接收包含关联实体的对象时出现400错误
我是ASP.NET Core新手,正在开发基于Entity Framework Core 6的WPF应用,调用ASP.NET Core 6 Web API时遇到问题。我尝试创建带有CreateContact方法的ContactController,但调用接口时返回400错误。
实体类代码
ContactEntity
public class ContactEntity : _EntityBase { private string _FirstName; public string FirstName { get { return _FirstName; } set { if (_FirstName != value) { _FirstName = value; RaisePropertyChanged("FirstName"); } } } public List<ContactEmailEntity> ContactEmails { get; set; } public ContactEntity() { ContactEmails = new List<ContactEmailEntity>(); } }
ContactEmailEntity
注意:该类包含指向ContactEntity的引用属性
[Table("ContactEmails")] public class ContactEmailEntity : _EntityBase { private string _EmailAddress = ""; public string EmailAddress { get { return _EmailAddress; } set { if (_EmailAddress != value) { _EmailAddress = value; RaisePropertyChanged("EmailAddress"); } } } [ForeignKey("ContactId")] public int? ContactId { get; set; } public ContactEntity? Contact { get; set; } }
控制器代码
[Route("api/[controller]/[action]")] [ApiController] public class ContactController : ControllerBase { [HttpPost] public IActionResult CreateContact([FromBody] ContactEntity myContact) { // Do some stuff return Ok(true); } }
错误信息
调用接口后返回400错误,详情如下:
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-b8c375d4c3f10c5097b982cac5b01c64-be98749a0187e8fb-00", "errors": { "myContact": [ "The myContact field is required." ], "$.contactEmails[0].contact": [ "The JSON value could not be converted to Entities.ContactEntity. Path: $.contactEmails[0].contact | LineNumber: 8 | BytePositionInLine: 25." ] } }
当前尝试与疑问
- 我发现如果移除ContactEmailEntity中的
Contact属性,接口就能正常运行并访问控制器 - 看到有建议使用DTO(如下示例),但这意味着我需要维护两个属性相似的类:一个实现
INotifyPropertyChanged用于WPF UI绑定,另一个作为POCO用于API数据传输,还要做数据映射,感觉比较繁琐
public class CreateContactInput { [Required] // Specify the data annotation attribute for property validation public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string CompanyName { get; set; } public string Title { get; set; } public string Suffix { get; set; } public string DisplayName { get; set; } public string Tags { get; set; } public string Notes { get; set; } public string EmailAddress { get; set; } }
我想知道:直接移除ContactEmailEntity中的Contact属性是否会带来其他问题?有没有更简便的替代方案?
内容的提问来源于stack exchange,提问作者CoderForHire
相关产品推荐
相关产品推荐

