Newtonsoft is not serializing navigation property

天涯浪子 提交于 2020-01-17 07:19:44

问题


I have an EF object RetailDocuments. It is related to the DocumentTemplateMaster object via foreign key. Many RetailDocuments can have the same 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.

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

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?

Edit: 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


回答1:


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.

Sometimes it's the simple things.




回答2:


You need to include your navigation property if you have lazy loading turned off

retailDocuments = db.RetailDocument.Include(x => x.DocumentTemplateMaster).where(x=>x.col2 = "someVal").ToList();

However note that Include has some notable performance impact. Often it is better to retrieve the values in 2 separate calls and add the relation in memory.



来源:https://stackoverflow.com/questions/38529085/newtonsoft-is-not-serializing-navigation-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!