簡體   English   中英

如何在Web API OData中發布具有導航關系的實體?

[英]How to POST an entity complete with navigational relationship in Web API OData?

我正在將ASP.NET Web API與OData一起使用。 我正在嘗試發布與父級 (父級已經存在)有關系的子級實體。 當我發布實體(使用WCF數據服務客戶端和SetLink)時,我可以通過Fiddler看到它正在向請求的主體中添加<link...href=[address of parent]> 此完全相同的請求適用於該服務的WCF數據服務版本(我們正在遷移到Web API)。 但是,這似乎沒有將任何內容轉換為Web API中控制器上的Post方法。

將孩子發布到ChildController時,如何通過ChildController上的Post操作訪問父母的ID? 我知道請求中存在該值,但是如何獲得該值? 沒有父母就不能創建孩子。 我是否需要修改控制器動作簽名? 也許我可以在某處使用某些屬性? 從API角度來看,如果可能的話,我想避免將ParentId直接添加到Child實體。

public class ChildController
{
    public HttpActionResult Post([FromBody]Child child)
    {
        //child.Parent is null here, but all other 
        //properties of Child are populated.
        //How can I get the Parent's ID from the POST request??
    }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Parent Parent { get; set; }
}

public class Parent
{
    public int Id { get; set; }
    public IEnumerable<Children> Children { get; set; }
}

編輯:這是我的要求。 我更改了一些名稱來保護無辜(替換的主機名和帶有父/子的實體名稱):

POST https://localhost/MyWebService/Child HTTP/1.1
Content-Type: application/atom+xml
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services

Host: localhost
Content-Length: 1048
Expect: 100-continue

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<category term="MyWebService.Entities.Child" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Parent" type="application/atom+xml;type=entry" title="Parent" href="https://localhost/MyWebService/Parents(1L)" />
<id />
<title /><updated>2014-05-30T16:07:28Z</updated><author><name /></author>
<content type="application/xml">
<m:properties>
<d:Content>content</d:Content>
<d:CreatedDate m:type="Edm.DateTime">0001-01-01T00:00:00</d:CreatedDate>
<d:Description>desc</d:Description>
<d:Enabled m:type="Edm.Boolean">true</d:Enabled>
<d:Id m:type="Edm.Int64">0</d:Id><d:TabName>tname</d:TabName>
</m:properties>
</content>
</entry>

為了從導航鏈接發布實體,您需要在父控制器中定義操作。 這是代碼片段:

public class ParentController
{
    public HttpActionResult PostToChildren(int key, [FromBody]Child child)
    {
        var parent = parents.single(p=>p.Id == key);
        if(parent != null)
        {
            parent.Children.Add(child);
            ChildController.Children.Add(child);
            return StatusCode(HttpStatusCode.NoContent);
        }
        else
            return BadRequest();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM