Web Api 2 - OData v3 - 插入多对多表odata查询

时间:2017-12-08 19:34:14

标签: entity-framework asp.net-web-api odata

我试图插入带有web api odata控件的多对多表格。

Db scheme

model

而我'用ef创建了带脚手架odata控制器的控件。 一切都很棒。我可以像这样查询用户表:

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
}

我已插入记录'管理员'手动。如何为用户添加新角色?

我已经尝试了,

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

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

它不起作用。你能救我吗?

1 个答案:

答案 0 :(得分:0)

或许迟到了,但有一个答案,它在docs.microsoft.com/...

上有描述

将以下CreateRef方法添加到UserController

[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”操作来执行此操作。