c# - How to Serialize in EF5 with ICollection<T> -


i'm using .net 4.5 , entity framework 5.0. have 3 basic entity classes created using code-first approach. i'm trying serialize , unable.

here's basics of classes:

base class

public class baseentity {   [key]   public int id {get; set;}    public datetime startdate { get; set; }   public datetime enddate { get; set; } } 

derived classes

public class childentity : baseentity {     public int parentid { get; set; }      [foreignkey("parentid")]     public parententity parententity { get; set; }      public string description { get; set; } }   public class parententity : baseentity {     public virtual icollection<childentity> rules { get; set; }      public rulegroup()     {       this.rules = new hashset<childentity>();     } } 

my context class

public class mydbcontext : dbcontext {     public dbset<parententity> parents { get; set; }     public dbset<childentity> childs { get; set; }      public mydbcontext()         : base("mydbcontext")     {     } } 

i've tryed serialize with:

using (var context = new mydbcontext()) {     using (var writer = xmlwriter.create(destinationfile))     {         var serializer = new xmlserializer(typeof(list<parents>));         serializer.serialize(writer, context.parents.tolist());     } } 

but looks can't serialize icollection<t>.

changed list<t> still gives me problems.

how can serialize\deserialize to\from xml simple structure of classes ? possible ?

another solution iterate collection yourself. you'll find still causes problems if using ef proxy classes change tracking/lazy loading (which looks me you have virtual icollection's).

using (var context = new mydbcontext()) {     using (var writer = xmlwriter.create(destinationfile))     {         var serializer = new xmlserializer(typeof(parent));         writer.writestartelement("arrayofparent");         foreach(parent parent in bdcontext.parents)         {             serializer.serialize(writer, parent);         }         writer.writeendelement();     } } 

you can turn proxies off this setting , doing should fix original code.

public class mydbcontext : dbcontext {     public mydbcontext ()     {         this.configuration.proxycreationenabled = false;     }     ... } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -