【问题标题】:How to Save/Update navigation property in Entity Framework?如何在实体框架中保存/更新导航属性?
【发布时间】: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&lt;Address&gt; 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


【解决方案1】:

如果您向员工发布地址列表,应该不会有问题。 问题是您发送模型的方式。 IList&lt;Addreess&gt; 是 JSON 中的对象数组。 IE:[{},{}] 您正在发送内部对象和对象。即:{{},{}} 按照问题中提供的建模,发送的 JSON 对象应该是这样的:

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

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多