如何在WCF RIA Services JSON端点上插入实体

如何在WCF RIA Services JSON端点上插入实体,json,rest,wcf-ria-services,domainservices,Json,Rest,Wcf Ria Services,Domainservices,我的WCF-RIA域服务有一个insert方法,如下所示: 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... } {"changeSet":[

我的WCF-RIA域服务有一个insert方法,如下所示:

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...
}
{"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 
        } 
    ] 
} 
要通过JSON端点访问此内容,我想我需要向url发布一个变更集:

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

我很确定我得到的URL是正确的,因为我的请求到达了WidgetService.Initialize方法,但随后我在服务器中遇到了一个异常——这并不奇怪,因为我不知道请求的内容应该是什么样子


我的问题:插入操作的HTTP请求内容的(JSON)格式是什么

所给示例的插入变更集如下所示:

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

感谢以下博文:

这是一个非常晚的答案,但只是为了防止其他人再次遇到这些问题;重要的是,
\u type
是实体中的第一个键

我遇到了如下例外情况:
此域服务不支持实体“对象”的操作“更新”
这表明域服务无法解析实体的类型,因此无法找到适当的处理程序

研究人员发现了这篇关于这个主题的博文,其中包含了解决方案

我想指出,这种行为违反了JSON规范(请参阅:)

一种可能的解决方法是使用
替换
,以确保
类型
位于正确的位置。我不相信这是一个好主意,但它确实奏效

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