簡體   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