Linq to sql DataContext cannot set load options after results been returned
Posted
by David Liddle
on Stack Overflow
See other posts from Stack Overflow
or by David Liddle
Published on 2010-05-06T10:25:27Z
Indexed on
2010/05/06
10:28 UTC
Read the original article
Hit count: 438
I have two tables A and B with a one-to-many relationship respectively.
On some pages I would like to get a list of A objects only. On other pages I would like to load A with objects in B attached.
This can be handled by setting the load options
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<A>(a => a.B);
dataContext.LoadOptions = options;
The trouble occurs when I first of all view all A's with load options, then go to edit a single A (do not use load options), and after edit return to the previous page.
I understand why the error is occurring but not sure how to best get round this problem. I would like the DataContext to be loaded up per request.
I thought I was achieving this by using StructureMap to load up my DataContext on a per request basis. This is all part of an n-tier application where my Controllers call Services which in turn call Repositories.
ForRequestedType<MyDataContext>()
.CacheBy(InstanceScope.PerRequest)
.TheDefault.Is.Object(new MyDataContext());
ForRequestedType<IAService>()
.TheDefault.Is.OfConcreteType<AService>();
ForRequestedType<IARepository>()
.TheDefault.Is.OfConcreteType<ARepository>();
Here is a brief outline of my Repository
public class ARepository : IARepository
{
private MyDataContext db;
public ARepository(MyDataContext context)
{
db = context;
}
public void SetLoadOptions(DataLoadOptions options)
{
db.LoadOptions = options;
}
public IQueryable<A> Get()
{
return from a in db.A
select a;
}
So my ServiceLayer, on View All, sets the load options and then gets all A's. On editing A my ServiceLayer should spin up a new DataContext and just fetch a list of A's.
When sql profiling, I can see that when I go to the Edit page it is requesting A with B objects.
© Stack Overflow or respective owner