Newtonsoft没有序列化导航属性

Newtonsoft没有序列化导航属性

本文介绍了Newtonsoft没有序列化导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个EF对象RetailDocuments.它通过外键与DocumentTemplateMaster对象相关.许多RetailDocuments可以具有相同的DocumentTemplateMaster.

I have an EF object RetailDocuments. It is related to the DocumentTemplateMaster object via foreign key. Many RetailDocuments can have the same DocumentTemplateMaster.

我正在检索List<RetailDocument>,并且已关闭代理创建和延迟加载.引用的DocumentTemplateMaster对象在列表中,但在序列化时不存在.

I'm retrieving a List<RetailDocument> and have turned off proxy creation and lazy loading. The referenced DocumentTemplateMaster object is there in the List but not when it is serialized.

我已经在SO和其他地方尝试了很多解决方案,但是由于某种原因,它对我不起作用.

I've tried a number of solutions I've seen here on SO and other places but for whatever reason, it's not working for me.

这是我的代码,带注释的代码显示了我尝试过的内容,但似乎没有什么不同:

Here's my code, commented code shows stuff I've tried but didn't seem to make a difference:

using (RetailDocumentEntities db = new RetailDocumentEntities()) {
    db.Configuration.ProxyCreationEnabled = false;
    db.Configuration.LazyLoadingEnabled = false;
    List<RetailDocument> retailDocuments =
    retailDocuments = db.RetailDocument.Include("DocumentTemplateMaster").where(x=>x.col2 = "someVal").ToList();

    JsonSerializerSettings serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };
string retVal = JsonConvert.SerializeObject(retailDocuments, Formatting.Indented, serializerSettings);

    //JsonSerializerSettings settings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Serialize};// PreserveReferencesHandling = PreserveReferencesHandling.Objects};// ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ReferenceLoopHandling = ReferenceLoopHandling.Serialize };
    //string retVal = Newtonsoft.Json.JsonConvert.SerializeObject(retailDocuments, settings);
    return retVal;
}

在我对其进行序列化之前,DocumentTemplateMaster会按其应有的方式在列表中显示为导航属性,但是在进行序列化时,它将丢失.我确定这是我所缺少的愚蠢的小东西,但这是什么?

Before I serialize it, DocumentTemplateMaster shows up as a navigation property in the List as it should but when serialized, it is missing. I'm sure it's a silly little thing I'm missing but what is it?

定义了上下文,并在其中包含.引用的DocumentTemplateMaster在检索列表中.这不是问题. 问题出在序列化中,因为它不在序列化的字符串中

the context is defined and the include is there. The referenced DocumentTemplateMaster is there in the retrieved list. This is not the problem. The problem is in the serialization as it is not in the serialized string

推荐答案

经过大量研究,似乎导航属性也需要具有[DataMember]属性.

After a lot more research, it would appear that navigation properties also need to have the [DataMember] attribute.

一旦我添加了,问题就消失了.

Once I added that, the problem went away.

有时候是简单的事情.

这篇关于Newtonsoft没有序列化导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:32