我有一个使用ASP创建的REST API。NET Web API 2和实体框架6。我想序列化/反序列化对象,并保留对其他对象的引用。
我在ASP中定义了一个标记模型类。NET,它还有一个由scaffolding生成的普通控制器类:
// C#
// Tag.cs
public class Tag
{
public int ID { get; set; }
public string Value { get; set; }
public Tag Parent { get; set; } // I know this can't be circular
}
...
// Context.cs
...
public DbSet<Tag> Tag { get; set; }
...
modelBuilder.Entity<Tag>().HasOptional(_ => _.Parent);
我正在用Python创建一个客户端
requests
和
jsonPickle
模块。我有一个用Python定义的等效类:
# Python
class Tag():
def __init__(self, jSrc=None):
#super(DBEntity,self).__init__()
self.ID = 0
self.Value = ""
self.Parent = None
if(jSrc != None):
self.__dict__ = jsonpickle.decode(jSrc)
以下Python代码可以正确地在Tags表中创建标记条目:
newTag = Tag()
newTag.Value = "Parent"
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post("http://server/api/Tags", data=jsonpickle.encode(newTag), headers=headers)
# ID | Value | Parent_ID
# 1 | Parent | -
但是,当我将父标记指定给设置了正确ID的标记对象时,会创建2个新标记条目,而不是使用父ID引用:
# Get Tag
rg = requests.get("http://server/api/Tags/1")
parentTag = Tag(rg.text)
# Create new Tag with Parent reference
newTag = Tag()
newTag.Value = "Child"
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post("http://server/api/Tags", data=jsonpickle.encode(newTag), headers=headers)
# ID | Value | Parent_ID
# 1 | Parent | -
# 2 | Parent | - << This should net be created
# 3 | Child | 2 << This should be 1
数据库现在包含2个“Parent”标记,但是“Child”标记的Parent_ID字段被正确设置为新的错误创建的“Parent”标记。
我怎样才能告诉ASP。NET系统来查找父标记的ID并保留对原始标记的引用,而不是将父属性反序列化为新的标记条目?