【发布时间】:2020-10-29 15:15:36
【问题描述】:
我正在使用 .Net 核心开发 Restful API。这里使用 Entity Framework Core(代码优先迁移)与 SQL Server 进行数据相关操作。
这里我的主要实体是:
public class Employee
{
public string Name { get; set; }
//...other properties.
public IList<Address> Addresses { get; set; }
}
public IList<Address> Addresses { get; set; } 是参考导航。
而Address 是一个依赖实体,看起来像:
public class Address
{
public string Address1 { get; set; }
//...other properties.
public Employee Employee { get; set; }
}
DbContext 是
public class OneToManyDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Address> Addresses { get; set; }
//..other config related connection string
}
Employee 的 API 控制器是
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
protected OneToManyDbContext _dbContext { get; set; }
public EmployeeController()
{
_dbContext = new OneToManyDbContext();
}
[HttpPost]
public void Add(Employee employee)
{
_dbContext.Employees.Add(employee);
_dbContext.SaveChanges();
}
}
对于与没有 Address 属性的 Employee 实体相关的 CRUD,一切正常。问题是如果我为 POST 方法发送嵌套的有效负载,例如
{
"name":"Dennis",
//..other properties,
"addresses": {
"address1":"Place name",
//..other properties
}
}
其中地址是嵌套键,因为地址属于员工。现在Add 方法失败了,因为它只期望Employee 没有Address 的对象。
错误消息是{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|8f31a2b1-4bcda017ebe85390.","errors":{"$.Addresses":["The JSON value could not be converted to System.Collections.Generic.IList'1[OneToManyRelationships.Models.Address]. Path: $.Addresses | LineNumber: 4 | BytePositionInLine: 15."]}}
我该如何解决这个问题。有什么我可以做的,比如序列化/反序列化过程。我正在关注存储库模式和工作单元,只是为了简化这个问题,我没有把它放在这里。
同样的问题也适用于更新/删除方法。
【问题讨论】:
-
输入参数employee有地址数据还是为空?
-
抛出的错误是什么?,发布两个对象应该不是问题
-
@Serge - 我正在传递实际值。即 "addresses": { "address1":"Place name", //..other properties } 如上所述。还用错误消息更新了我的问题。
-
@RodrigoRamírez - 我用错误消息更新了我的问题。提前致谢。
-
你是使用ajax发布数据还是提交表单?
标签: c# rest entity-framework-core ef-code-first