Pergunta

I have been doing research, this question looks to be being answered before, but not exactly to what I need. In short, I am using EF5, with lazy loading, objects returned from database are all proxy types, and my WCF web service need to return them thru rest as json format. After knowing that Proxy Types cannot be serialized, I attempted to use ApplyDataContractResolverAttribute + ProxyDataContractResolver to convert Proxy Type back to POCO type before responding. Unfortunately after adding ProxyDataContractResolver, DataContractSerializer still trying to serialize the Proxy Type and giving me serialization exception. A lot of online solution involves turning lazy loading off or ProxyCreationEnabled off

My first question is: does it exist a solution where I can still leverage the lazy loading from EF, and still able to serialize POCO type back as Json to my client?

My second question is: what should be the best practice for my situation?

Thanks a lot for your help in advance

Foi útil?

Solução

The best thing to do is configure your models and tell which properties should be mapped. Like this there won't be an overload of data. Using the ScriptIgnore attribute should work.

Example:

[Serialize]
public class Person{
  public int ID {get;set;}
  public virtual List<Role> Roles {get;set;}
  //other properties
}
[Serialize]
public class Role{
  public int ID {get;set;}
  [ScriptIgnore]
  public virtual List<Person> PersonsInRole {get;set;}
  //other properties
}

In the example the roles for the user will be mapped, but the navigation property PersonsInRole of Role will not be serialized to prevent the overflow.

For the second question. the easiest way is just to use JSON.NET to serialize.

Outras dicas

I end up restructured my EF data model (to avoid cycles) and gave up on using lazy loading.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top