none
LINQ objects serialization RRS feed

  • Question

  • Hi All,

    I need to serialize some entities from sql server database to xml for backup purposes. I select entities using LINQ query and then serialize the result using DataContractSerializer. The serialization mode of DataContext is set to Unidirectional. The entities have some subentities which are loaded using deferred loading. Well, actually they don't. The subentities are not serialized unless I call some properties of the subentities thus triggering the loading of them. This doesn't look too elegant. Does anyone know any way to trigger deferred loading during serialization?

    Thanks
    Artem
    Monday, May 18, 2009 8:42 AM

Answers

  • It sounds like you could specify eager-loading for the required entities.

    DataLoadOptions dlo = new DataLoadOptions();
    dlo.LoadWith<Customer>(o => o.Orders); // Loads all related order entities
    dlo.LoadWith<Customer>(o => o.Branch); // Loads branch entity
    dlo.LoadWith<Order>(o => o.LineItems); // Loads order items with each order

    DataContext db = new DataContext();
    db.LoadOptions = dlo;
    db.ObjectTrackingEnabled = false; // You might want to try this for performance gain if you're simply serialising the loaded entities

    // Now query for your entities...
    Monday, May 18, 2009 10:04 AM
    Answerer

All replies

  • It sounds like you could specify eager-loading for the required entities.

    DataLoadOptions dlo = new DataLoadOptions();
    dlo.LoadWith<Customer>(o => o.Orders); // Loads all related order entities
    dlo.LoadWith<Customer>(o => o.Branch); // Loads branch entity
    dlo.LoadWith<Order>(o => o.LineItems); // Loads order items with each order

    DataContext db = new DataContext();
    db.LoadOptions = dlo;
    db.ObjectTrackingEnabled = false; // You might want to try this for performance gain if you're simply serialising the loaded entities

    // Now query for your entities...
    Monday, May 18, 2009 10:04 AM
    Answerer
  • Thanks! Just what I need.
    Monday, May 18, 2009 12:09 PM