Creating an object with a link to another object in the azure mobile service

I created an azure mobile service, which mainly consists of 2 entities and 2 TableControllers. Both of these objects have a 1: 1 ratio.

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; } } 

Controllers are standard scaffold controllers. When I try to insert an instance of entity1 with reference to an existing entity2, I get the following message:

 {"$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.'."} 

I used the following JSON in the request body:

 { "value": 1, "date": "2015-04-27T06:51:47.641Z", "name": "name", "project": { "id": "32aec44a282e42b7bc51096052335dad", } } 

Can I use an existing object as a reference in the .NET Code First / Azure Mobile Service? I'm not quite sure if this is a question related to EF CodeFirst or the azure mobile service.

Thanks.

+6
source share
2 answers

The default behavior for inserting Entity1 also attempts to insert a nested link. If this value is already inserted, then such a conflict may occur.

One option would be to change the insert code to treat the nested element as already inserted, as in the section "Attaching an Existing Entity to the Context" https://msdn.microsoft.com/en-us/data/jj592676.aspx

Moreover, this blog post can be useful: http://blogs.msdn.com/b/azuremobile/archive/2014/06/18/insert-update-related-data-with-1-n-relationship-using -net-backend-azure-mobile-services.aspx

0
source

We tried to do the same, but did not care about updating the related objects themselves. If you want to update an object containing links to related objects, you can simply attach them to the context and you will not get PK violation errors:

enter image description here

0
source

Source: https://habr.com/ru/post/986034/


All Articles