【问题标题】:Insert record with relationship using OData使用 OData 插入具有关系的记录
【发布时间】:2016-08-27 02:27:48
【问题描述】:

这就是我的模型的样子

public User
{
    public string Id { get; set; }
    public string Username { get; set; }
    public virtual Group Group { get; set; }
}

public Group
{
    public string Id { get; set; }
    public string Name{ get; set; }
    public virtual ICollection<User> Users { get; set; }
}

我使用 Azure Mobile TableController,它使用 OData 进行 CRUD。

现在我尝试通过指定组的 id 来插入新用户,但它给了我一个错误,表明它没有尝试将其与我的用户模型相关联,而是尝试创建新用户:

{
  "message": "The operation failed due to a conflict: 'Violation of PRIMARY KEY constraint 'PK_dbo.Groups'. Cannot insert duplicate key in object 'dbo.Groups'. The duplicate key value is (ad934511a82c4b42ae5427b5228737c6).\r\nThe statement has been terminated.'."
}

这就是我的帖子的样子:

POST http://localhost/tables/user?ZUMO-API-VERSION=2.0.0 HTTP/1.1

{
    email: 'test@test.com',
    password: '#test',
    group: {
        id: 'ad934511a82c4b42ae5427b5228737c6'
    }
}

【问题讨论】:

    标签: asp.net azure odata azure-mobile-services


    【解决方案1】:

    Azure 移动应用程序不直接支持关系,但您可以应用一些变通方法使其正常工作。这是一篇介绍该场景的博文:30 Days of Zumo.v2 (Azure Mobile Apps): Day 26: Relationship Advice

    您遇到的具体问题是实体框架“分离实体”问题。参见例如Many to Many Relationships not saving。问题是实体框架没有将子项加载到其上下文中,因此它认为它需要插入子项以及父项。 (Entity Framework 长期以来一直有功能要求解决这个问题,但从未添加过该功能。)

    我刚刚在这里发布了一个类似的答案:How do I insert entities with a 1:n relationship in Azure App Service

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      相关资源
      最近更新 更多