繁体   English   中英

如何在实体框架中保存/更新导航属性?

[英]How to Save/Update navigation property in Entity Framework?

我正在使用 .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; } 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
                 } 
}

其中addresses 是嵌套键,因为address 属于Employee。 现在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."]}}

我该如何解决。 有什么我可以做的,比如序列化/反序列化过程。 我正在遵循存储库模式和工作单元,只是为了简化这个问题,我没有把它放在这里。

同样的问题也适用于更新/删除方法。

如果您向员工发布地址列表,应该不会有问题。 问题在于您发送模型的方式。 IList<Addreess>是 JSON 中的对象数组。 IE : [{},{}]你在内部发送一个对象而不是对象。 IE: {{},{}}按照问题中提供的建模,发送的 JSON 对象应该是:

{
    name: "string",
    //other values
    addresses: 
    [
        {
           "address1":"string",
           //other properties
        },
        {
           "address1":"another string"
           //some other properties
        }
    ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM