Serializable classes and dynamic proxies in EF - how?

前端 未结 5 452
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 12:08

In [a previous posting], I was set on the path to having to clone my entities. This I\'ve attempted to do with a serialisation approach as found in [codeproject].

b

相关标签:
5条回答
  • 2020-11-29 12:30

    I had the same issue using Entity Framework 6 ( EF6 ). I fixed the issue by changing the T4 template and adding the line [Serializable] between the Using Directives and the Entity Class Opening line. Like so:

     <#=codeStringGenerator.UsingDirectives(inHeader: false)#>
     [Serializable]
     <#=codeStringGenerator.EntityClassOpening(entity)#>
    

    No other changes required.

    0 讨论(0)
  • 2020-11-29 12:37

    Look into T4 Templates for Entity Framework, you can control how EF generates your entities, you will have to define that they are serializable in the T4 Template.

    0 讨论(0)
  • 2020-11-29 12:40

    Turn off lazy loading and turn off proxy class creation. Anyway you still need to add the Serializable/DataContract attributes in order to make it serializable.

    0 讨论(0)
  • 2020-11-29 12:48

    If you want to serialize entities you can disable proxy creation before retrieving that object. You also need to eager load navigational properties if you want to serialize them as well.

    To disable proxy creation in EF 4.1

    dbContext.Configuration.ProxyCreationEnabled = false;
    

    In EF 4

    objectContext.ContextOptions.ProxyCreationEnabled = false;
    

    eg:

    var users = context.Users.Include("Claims").Where(/**/);
    
    0 讨论(0)
  • 2020-11-29 12:49

    As a Microsoft recommendation, you need to use DTO instead of EF entities to avoid serialization issues, consider also to use eager loading before transforming your entities to DTO.

    One way to avoid serialization problems is to serialize data transfer objects (DTOs) instead of entity objects.

    ...

    What happens if you add the corresponding navigation property [...]?

    Unfortunately, this creates a problem when you serialize the models. If you load the related data, it creates a circular object graph.

    One solution is to use DTOs, [...] Alternatively, you can configure the JSON and XML formatters to handle graph cycles.

    EF Documentation - How to create a Web API application that uses Entity Framework for database persistence.

    0 讨论(0)
提交回复
热议问题