I use LINQ 2 SQL in one of my projects and i have numerous relationships Customer -> Documents1, Documents2, Documents3, Address, Invoices etc....
When using the LoadWith(p => p.Documents1)...etc I have performance issues, imagine 2000 customers with all these numerous relationships loaded in List in memory!
The other way around Document -> Customer its not so much an issue as the relationship its light.
So i try to remove all the LoadWith and just leave the Customer -> Address relationship. Now if i go and open a Document1 and then open my Customers i get an object disposed exception when i serialize my Customers. The serialize method basically throws this exception.
The serialize Method:
public static T CloneObjectGraph<T>(this T obj) where T : class
{
var serializer = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null);
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Position = 0;
return (T)serializer.ReadObject(ms);
}
}
The Method i get the Customers:
public List<Customer> GetCustomers()
{
using (MyDataContext db = new MyDataContext(MyDataContextManager.ConnectionString))
{
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Customer>(p => p.Address);
dlo.LoadWith<Customer>(p => p.Documents1);
dlo.LoadWith<Customer>(p => p.Documents2);
dlo.LoadWith<Customer>(p => p.Documents3);
dlo.LoadWith<Customer>(p => p.Documents4);
dlo.LoadWith<Customer>(p => p.Documents5);
dlo.LoadWith<Customer>(p => p.Documents6);
dlo.LoadWith<Customer>(p => p.Documents7);
dlo.LoadWith<Customer>(p => p.Documents8);
dlo.LoadWith<Customer>(p => p.Documents9);
dlo.LoadWith<Customer>(p => p.Documents10);
dlo.LoadWith<Customer>(p => p.Documents11);
db.LoadOptions = dlo;
return db.Customers.ToList();
}
}
I want to remove all the LoadWith except Address relationship. I hate when this error is not reproduce always but in some cases i couldn't find.
I could guess the DataContractSerializer constructor for a change but i cant get it right.
Any help appreciated!