How to insert entity over WCF-RIA-Services JSON endpoint

浪尽此生 提交于 2019-12-12 03:22:43

问题


My WCF-RIA DomainService has an insert method that looks like this:

public void InsertWidget(WidgetDef widgetDef)

class WidgetDef
{
    [Key]
    int widgetID;
    string title;
    int x;
    int x;
    // there are more properties, but I think you get the idea...
}

To access this through the JSON endpoint, I think I need to POST a changeset to the url:

[serverURL][namespace]WidgetService.svc/json/SubmitChanges.

I'm pretty sure I got the URL correct, because my request reaches the WidgetService.Initialize method, but then I get an exception in the server - which is no surprise because I don't know what the content of the request should look like.

My Question: What is the (JSON) format of a HTTP request's content for an insert operation?


回答1:


Insert changeset for the example given would look like this:

{"changeSet":[ 
        {"Id":0, 
         "Entity":{"__type":"WidgetDef:#widgetDefNamespace",
                    "widgetId":0, 
                    "title":"the new title", 
                    "x":10, 
                    "y":10, 
                }, 
            "Operation":2    // '2' for insert, '3' for update, '4' for delete 
        } 
    ] 
} 

Thanks to following blog post: http://www.joseph-connolly.com/blog/post/WCF-RIA-Services-jQuery-and-JSON-endpoint-Part-2.aspx




回答2:


This is a very late answer, but just in case someone else runs into these issues again; it is important that the __type is the first key in the entity.

I ran into exceptions like: This DomainService does not support operation 'Update' for entity 'Object' which indicate that Domain Service was unable to resolve the type of the entity, and therefor unable to find the appropriate handler.

Research turned up this blogpost on the subject http://www.blog.yumasoft.com/node/108 which contains the solution.

I'd like to point out that this behavior goes against the JSON specification (see: https://stackoverflow.com/a/5525820/1395343).

One possible workaround is to use replace to ensure that the __type ends up in the correct location. I'm not convinced that this is a good idea, but it does work.

var entityChange = {};
entityChange.Id = 0;
entityChange.Operation = 3;
entityChange.Entity = {'key': 'Something that changed'};

var payload = JSON.stringify({ changeSet: [entityChange]});

// This is not an ideal way of doing this.
payload = payload.replace('"Entity":{', '"Entity":{"__type":"TypeName:#Namespace.Stuff",');
return $.ajax({
    url: "...Web.svc/JSON/SubmitChanges",
    method: "POST",
    data: payload,
    contentType: "application/json",
    dataType: "json",
    processData: false,
});


来源:https://stackoverflow.com/questions/8179504/how-to-insert-entity-over-wcf-ria-services-json-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!