2

I have this Entity class:

 public class Foo{
        [Key]
        [Column("ENT_ID")]
        public int Id { set; get; }

        .....

        [NotMapped]
        public virtual Employee Employee{ set; get; }

        [NotMapped]
        public virtual List<Car> Cars{ set; get; }

        [NotMapped]
        public virtual List<Book> Books{ set; get; }

        public Foo()
        {
            Books= new List<Book>();
            Cars= new List<Car>();
        }
    }

I would to exclude virtual properties from serialization, using [NotMapped] worked but I am not able to navigate to this properties! I tried to use [XMLIgnore] but did not help.

I use this serialize class:

public class XmlSerializer<T> where T : class
    {
        public static string Serialize(T data)
        {
            var sw = new StringWriter();
            var xmlSerializer = new XmlSerializer(typeof(T));
            xmlSerializer.Serialize(sw, data);
            return sw.ToString();
        }

        public static T Deserialize(string data)
        {
            var ser = new XmlSerializer(typeof(T));
            var sr = new StringReader(data);
            return (T)ser.Deserialize(sr);
        }
    }

How to exclude virtual properties from serialization and still use them as navigation properties?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272

1 Answers1

1

You need to remove the generated proxy from the entity before serializing. To get the object without EF generating the proxy you'll have to disable the proxy creation and than convert it to an object. Like so:

dbCcontext.Configuration.ProxyCreationEnabled = false;
Foo foo = dbContext.Entry(fooLoadedWithEF).CurrentValues.ToObject() as Foo;
// Do your serialization of 'foo'

Don't forget to set the ProxyCreationEnabled back to it's original value afterwards.

There's a nice method that does this in an answer about removing the proxy here: https://stackoverflow.com/a/25774651/31722

Sorskoot
  • 10,190
  • 6
  • 55
  • 98