【发布时间】:2014-05-06 12:33:48
【问题描述】:
我目前在Core Data 数据库中有许多实体,Web API 后端服务JSON。每个实体在服务器上都有一个单独的端点,该端点返回数据库中的所有这些实体,例如
.../api/student
.../api/teacher
.../api/degree
etc
JSON 被序列化以包含外键 ID。下面是一个学生的示例响应:
[
{
"studentID" : 1,
"degree" : {
"degreeID" : 1
},
"name" : "My Name",
"teachers" : [
{ "teacherID" : 1 },
{ "teacherID" : 2 }
]
}
]
“学生、教师、学位”设计是一个虚构的例子,不幸的是,真正的数据库更复杂,有很多“one-to-many”和“many-to” -many' 关系。
我是 RestKit 的新手,不确定为 Core Data 请求和处理这些数据的最佳方式。当应用程序启动时,我只需要应用程序更新其Core Data 数据库以匹配Web API 版本。任何关于如何最好地请求每个端点和处理映射的指导将不胜感激。例如,在我可以导入上面的JSON 之前,我是否需要已经请求并存储了学位和教师?我可以完全控制客户端和服务器。
编辑:添加示例代码
下面是一些类似于我的示例代码。我尝试了许多不同的方法(例如 addRelationshipMappingWithSourceKeyPath 和 addConnectionForRelationship)来处理从学生到教师的“多对多”关系,但是我似乎总是收到以下错误:
relationship 'teachers' fault on managed object
示例代码:
RKEntityMapping *studentMapping = [RKEntityMapping mappingForEntityForName:@"Student" inManagedObjectStore:managedObjectStore];
studentMapping.identificationAttributes = @[ @"id" ];
[studentMapping addAttributeMappingsFromDictionary:@{@"name" : @"name"}];
RKEntityMapping *teacherMapping = [RKEntityMapping mappingForEntityForName:@"Teacher" inManagedObjectStore:managedObjectStore];
tagMapping.identificationAttributes = @[ @"id" ];
[teacherMapping addAttributeMappingsFromDictionary:@{@"name" : @"name"}];
/*** RELATIONSHIP CONNECTION ***/
[studentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"teachers" toKeyPath:@"id" withMapping:teacherMapping]];
/*** RESPONSE DESCRIPTORS ***/
RKResponseDescriptor *studentResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:studentMapping method:RKRequestMethodGET pathPattern:@"/api/student" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:studentResponseDescriptor];
RKResponseDescriptor *teacherResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:teacherMapping method:RKRequestMethodGET pathPattern:@"/api/teacher" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:teacherResponseDescriptor];
【问题讨论】:
-
每个端点都提供了一种类型的所有详细信息以及它与 id 之间的所有关系?并且您想在应用启动时调用所有端点?
-
是的。目前,我为每种类型/实体都有一个单独的端点。由于我需要 Core Data 数据库与服务器的版本完全匹配,我相信我需要依次调用每个端点。
-
你不能同时调用它们,但除此之外你应该没有问题。查看有关外键映射和获取请求块的其他答案。
-
我是否需要按顺序调用它们,即上面示例中的“学生”之前的“度”(因为“学生”引用“度”)?数据库有一些循环引用,如果不是不可能的话,这会使这变得很棘手。
标签: ios json entity-framework core-data restkit