问题
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