【问题标题】:Web Api 2 - OData v3 - insert many-to-many table odata queryWeb Api 2 - OData v3 - 插入多对多表 odata 查询
【发布时间】:2018-08-07 04:34:42
【问题描述】:

我正在尝试使用 web api odata 控件插入多对多表。

我已经创建了带有 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)"
        }
    ],
}

它没有用。你能帮帮我吗?

【问题讨论】:

  • 我需要向控制器添加新动作吗?我不想表现得不规范

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


【解决方案1】:

也许有点晚了,但有一个答案,描述在: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”操作来执行此操作。

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多