2017-12-08 14 views
1

웹 API 오타타 제어를 사용하여 다 대다 테이블을 삽입하려고합니다.Web API 2 - OData v3 - 다 대다 테이블 odata 쿼리를 삽입하십시오.

model

Db scheme

그리고 'EF와 비계의 하나로, OData 컨트롤러로 만든 컨트롤을했습니다. 모든 것이 greate입니다. 다음과 같이 사용자 테이블을 쿼리 할 수 ​​있습니다.

GET http://localhost:51875/odata/Users(1)?$expand=Roles 

{ 
    "odata.metadata": "http://localhost:51875/odata/$metadata#Users/@Element", 
    "Roles": [ 
     { 
      "ID": 20, 
      "Name": "Admin" 
     } 
    ], 
    "ID": 1, 
    "UserName": "user", 
    "Password": "pass", 
    "EnteredDate": "2017-12-07T14:55:22.24", 
    "LastLoginDate": null, 
    "Active": true 
} 

'Admin'레코드를 수동으로 삽입했습니다. 사용자에게 새 역할을 추가하려면 어떻게합니까?

나는 시도했다, 그것은 작동하지 않았다

PATCH http://localhost:51875/odata/Users(1) 

{ 
    "Roles": [ 
     { 
      url : "http://localhost:51875/odata/Roles(10)" 
     } 
    ], 
} 

. 너 나 좀 도와 줄 수있어? 당신의 UserController에 다음 CreateRef 방법을 추가 docs.microsoft.com/...

:

+0

컨트롤러에 새 작업을 추가해야합니까? 나는 비상 한 행동을하고 싶지 않다. –

답변

0

비트 늦게 아마도하지만,이에 대한 답변이, 그것은에 설명되어 있습니다

이제
[AcceptVerbs("POST", "PUT")] 
public IHttpActionResult CreateRef([FromODataUri] int key, string navigationProperty, [FromBody] Uri link) 
{ 
    var user = Db.Users 
      .FirstOrDefault(p => p.Id == key); //Get User by id 
    if (user == null) 
    { 
     return NotFound(); 
    } 

    switch (navigationProperty) 
    { 
     case "Roles": 
      // You'll have to impement this 'getkey' method somehow. 
      // You could implement it yourself or take a look on the webpage I linked earlier. 
      var relatedKey = GetKeyFromUri(link); 
      var role = Db.Roles 
        .FirstOrDefault(f => f.Id == relatedKey); //Get Role by id 
      if (role == null) 
      { 
       return NotFound(); 
      } 

      user.Roles.Add(role); 
      break; 

     default: 
      return StatusCode(HttpStatusCode.NotImplemented); 
    } 
    Db.SaveChanges(); 
    return StatusCode(HttpStatusCode.NoContent); 
} 

당신이 사용자에게 역할을 추가 할 수 있습니다 다음 HTTP 요청 :

PUT [...]/api/User(2)/Roles/$ref 
Content-Type: application/json 
Content-Length: 54 
{ "@odata.id": "[...]/api/Role(4)/" } 

개인적으로이 방법은 특히 좋지만 표준입니다. 또한 주석에서 언급 한 것처럼 사용자 정의 'AddRoles'액션을 사용하여이 작업을 수행 할 수 있습니다.