在azure移动服务中创建引用其他实体的实体

Sve*_*ach 6 c# entity-framework azure ef-code-first azure-mobile-services

我创建了一个天蓝色的移动服务,它基本上由2个实体和2个TableControllers组成.这两个实体都有1:1的关系.

public class Entity1 : EntityData
{
    public int Value { get; set; }
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public virtual Entity2 Reference { get; set; }
}

public class Entity2 : EntityData
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器是标准的脚手架生成的控制器.当我尝试插入一个entity1实例并引用已经存在的entity2时,我得到以下消息:

{"$id":"1","message":"The operation failed due to a conflict: 'Violation of 
PRIMARY KEY constraint 'PK_Service.Entity2'. Cannot insert
duplicate key in object 'Service.Entity2'. The duplicate key
value is (32aec44a282e42b7bc51096052335dad).\r\nThe statement has been 
terminated.'."}
Run Code Online (Sandbox Code Playgroud)

我在请求正文中使用了以下JSON:

{
  "value": 1,
  "date": "2015-04-27T06:51:47.641Z",
  "name": "name",
  "project": {
    "id": "32aec44a282e42b7bc51096052335dad",
  }
}
Run Code Online (Sandbox Code Playgroud)

是否可以在.NET Code First/Azure Mobile Service中使用现有实体作为参考?我不太确定这是否是更多EF CodeFirst或azure移动服务相关问题.

谢谢.

小智 0

默认行为是插入 Entity1 时也会尝试插入嵌套引用。如果该值已被插入,则可能会发生此类冲突。

一种选择是修改插入代码以将嵌套项视为已插入,如https://msdn.microsoft.com/en-us/data/jj592676 的“将现有实体附加到上下文”部分中所示。 ASPX

有关更多信息,此博客文章可能会有所帮助: http://blogs.msdn.com/b/azuremobile/archive/2014/06/18/insert-update-lated-data-with-1-n-relationship-using-网络后端-azure-移动-services.aspx