微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在使用.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方法

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。