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

时间:2020-10-29 15:15:36

标签: c# rest entity-framework-core ef-code-first

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

对于仅具有Employee属性的Address实体相关的CRUD,一切正常。问题是,如果我将POST方法的嵌套有效负载发送给

{ 
    "name":"Dennis",
    //..other properties,
    "addresses": {
                     "address1":"Place name",
                     //..other properties
                 } 
}

,其中地址是嵌套键,因为地址属于Employee。现在Add方法失败了,因为它只希望没有Employee的{​​{1}}对象。

错误消息为Address

如何解决此问题。有什么我可以做的事情,例如序列化/反序列化过程。我正在遵循“存储库模式”和“工作单元”,只是为了简化此问题,我并未在此处放置它。

相同的问题也适用于Update / Delete方法。

1 个答案:

答案 0 :(得分:1)

如果您发布带有地址列表的员工,应该没有问题。 问题在于您发送模型的方式。 IList<Addreess>是JSON中的对象数组。 I.E:[{},{}]是您在内部发送一个对象,而是发送了一个对象。即:{{},{}} 按照问题中提供的建模,发送的JSON对象应满足以下条件:

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