Ryan
Ryan

Reputation: 6517

IQueryable collection lazy property setting on object

I have the following code:

var carsContext = new CarsDataContext();

IQueryable<Car> allCars = carsContext.Cars;

foreach (var car in allCars) 
    Console.WriteLine(car.Color);

What I'd like is for each car object to be aware of the original datacontext that was used to retrieve it, so that I can decorate it with helper methods like the following:

foreach (var car in allCars)
    Console.WriteLine(car.GetOwner().Lastname);

with the GetOwner() method being able to automatically reuse the original datacontext for the next database, whereas right now I have to do some ugliness to get that same effect:

foreach (var car in allCars)
{
    car.SetDataContext(carsContext);
    Console.WriteLine(car.GetOwner().Lastname);
}

Is this information already available to the objects, or should I try making a custom IQueryable implementation that will auto-assign this for me when the objects are retrieved from the collection?

I'm trying to do this this way because I want to preserve deferred evaluation of the expression against the database as SQL for performance reasons (I have large datasets).

Any advice is appreciated, thanks.

EDIT: This is the simplified example, for example the reference to the original data context is not immediately available necessarily.

Upvotes: 2

Views: 386

Answers (1)

Ryan Bennett
Ryan Bennett

Reputation: 3432

Are you using EF? You can do an .Include(c => c.Owner) when you initially get the car entity. Lazy loading is preserved but now you get the Owner entity along with the Car. Also, it may improve performance as you are doing a 1 join query vs going back to the db 100 times for each car instance.

Upvotes: 2

Related Questions