How do I update an OData entity and modify its navigation properties in one request?

前端 未结 3 510
花落未央
花落未央 2020-12-31 23:43

I am trying to implement what I thought was a simple scenario using an OData service provided by WCF Data services (using the OData V3 application/json;odata=verbose payload

相关标签:
3条回答
  • 2021-01-01 00:20

    I found two ways to represent navigation properties inline:

    application/json;odata=verbose - { "Name": "new name", "Category": { "__metadata": { "uri": "Categories(2)" }}}

    application/json - { "Name": "new name", "Category@odata.bind": "Categories(2)" }

    0 讨论(0)
  • 2021-01-01 00:31

    You don't need a batch, anymore. You can do it in one call. You simply need to also send up the changed properties and let the repository handle the changed properties.

    public class Person 
    {
       public string FirstName {get;set;}
       public string LastName {get;set;}
       public int Age {get;set;}
    }
    

    Let's say you notice the first name has a typo, Jhon and it is supposed to be John. You can edit the first name and send it up. So you have the following object model. You can get this in 1 of two ways:

    • Have two parameters and set BodyStyle = WebMessageBodyStyle.Wrapped
    • Just create a generic model object with two properties: Property one is of Type T and property 2 is a List.

    So you would send up this json:

    [{ FirstName = 'John' }, ['FirstName']]
    

    Now on the server side, you can do what you need to do.

    If you don't want to send the changed properties, you can guess the changed properties by choosing any property whose value isn't the default property.

    { FirstName = 'John' }

    Then you can use a few methods to see what properties have changed:

    • Custom code per entity to make sure that each property is not the default value and set it. Requires a piece of code per entity.
    • Reflection to make sure that each property is not the default value. Requires 1 class for all entities. I did this back in 2014 here in Entity Framework: http://www.rhyous.com/2014/12/01/entityupdater-generic-helper-for-entity-framework/
    0 讨论(0)
  • 2021-01-01 00:32

    Pratik's comment was the answer (Pratik if you'd like to repost this as an answer, I'll mark it as such - thanks!):

    Question: Do you want to update the category instance or do you want to update some of the properties of the category instance. There is no way to do the later other than batch. For the former, you can do something like: { "Name" : "new name", "Category" : { "__metadata" : { "uri" : "/api.svc/Categories(2)" }}}. Hope this helps. – Pratik

    0 讨论(0)
提交回复
热议问题