【发布时间】:2016-04-22 04:28:14
【问题描述】:
这个问题源于另一个article。我目前正在将 BreezeJS 与 Entity Framework 一起使用,但我不相信我正在按照预期的方式使用它。目前,我正在对发送到服务器的实体数组调用保存更改,然后将它们反序列化为原始结构。我希望有更好的方法来做到这一点,我只是无法找到。我认为有两种方法可以做到这一点,但无法让它们发挥作用。
首先将数组作为单个对象发送,当反序列化时,该对象已经在对象结构中。当客户端是对象的格式时,它不会采取任何额外的工作。
第二种选择是以某种方式使用发送到服务器的数组,并使用 EFContextProvider 中的实体框架元数据构建对象结构。
如果可能的话,我更喜欢更接近选项一的解决方案。
Javascript
function saveObjects() {
// Assume the child class has a foreign key to the parent
var parent = dataService.createEntity('PARENT', parentObject);
var child = dataService.createEntity('CHILD', childObject);
// Save changes
// This is what I'm currently doing because each entity is seperate
dataService.saveChanges([parent, child]);
// This is what I would like to do
// dataService.saveChanges(parent);
}
当前发送的对象如下所示。我希望 CHILD 在发送时实际上是 PARENT 对象中的子对象。
// Current saveBundle
{"entities": [
{"ID: 1,
"entityAspect": {"entityTypeName": "PARENT", ...}},
{"PARENT_ID: 1,
"entityAspect": {"entityTypeName": "CHILD", ...}}
]}
// Ideal saveBundle
{"entities": [
{"ID: 1,
{"PARENT_ID: 1,
"entityAspect": {"entityTypeName": "CHILD", ...}},
"entityAspect": {"entityTypeName": "PARENT", ...}},
]}
C#
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
// Currently I have to deserialize each object and rebuild the object
// because the save bundle is a list of single entities instead of
// the existing object hierarchy
PARENT parent = DeserializeEntity(saveBundle, 'PARENT');
parent.child = DeserializeEntity(saveBundle, 'CHILD');
// Custom Validation and Saving is done here
}
我可能错误地使用了 BreezeJS,但验证和数据库保存发生在后面的单独模块中。我只是想减少一些中间的手动工作(必须重建对象结构)。
【问题讨论】:
-
即使实体在客户端是相关的,Breeze 也会将它们拆分为一个数组,以避免在序列化为 JSON 时出现循环引用问题。在服务器上,EFContextProvider 将它们添加到 EF 上下文中; EF 在此过程中自动重建对象图。
-
这就是问题所在,我找不到任何如何做到这一点的例子。在服务器上,我有发送的实体数组,但我不知道如何使用我的 EFContextProvider 从数组构建我的对象。
-
但是为什么它会自动为你做呢?
-
因为我要控制保存。一旦数据到达控制器,我将重建结构并在对象本身内进行数据验证。一旦他们通过了验证,我就会使用 EF 提交到数据库。目前系统工作正常,如果可能的话,我只想退出手动重建数据结构。