views:

215

answers:

2

The buzword in Linq now days is "unit of work". as in "Only keep your datacontext in existence for one unit of work" then destroy it.

Well I have a few questions about that.

  1. I am creating a fat client WPF application. So my data context needs to track the entire web of instantiated object available for the user on the current screen. when can I destroy my datacontext?
  2. I build a linq query over time based on actions of the user and their interactions with objects of the first datacontext. How can I create a new DataContext and execute the query on new Context?

I hope I was clear. Thank you

A: 

Unit of Work is not the same as only keep your datacontext in existence for one unit of work.

Unit of Work is a design pattern that describe how to represent transactions in an abstract way. It's really only required for Create, Update and Delete (CUD) operations.

One philosophy is that UoW is used for all CUD operations, while read-only Repositories are used for read operations.

In any case I would recommend decoupling object lifetime from UoW or Repository usage. Use Dependency Injection (DI) to inject both into your consuming services, and let the DI Container manage lifetimes of both.

In web applications, my experience is that the object context should only be kept alive for a single request (per-request lifetime). On the other hand, for a rich client like the one you describe, keeping it alive for a long time may be more efficient (singleton lifetime).

By letting a DI Container manage the lifetime of the object context, you don't tie yourself to one specific choice.

Mark Seemann
A: 

I am creating a fat client WPF application.

Ok.

So my data context needs to track the entire web of instantiated object available for the user on the current screen.

No. Those classes are database mapping classes. They are not UI presentation classes.


How can I create a new DataContext and execute the query on new Context?

Func<DataContext, IQueryable<Customer>> queryWithoutADataContext =
  dc =>
    from cust in dc.Customers
    where cust.name == "Bob"
    select cust;

Func<DataContext, IQueryable<Customer>> moreFiltered =
  dc =>
    from cust in queryWithoutADataContext(dc)
    where cust.IsTall
    select cust;

var bobs = queryWithoutADataContext(new DataContext);
var tallbobs = moreFiltered(new DataContext);
David B
Thank you for part 2it was very helpful
Rabbi
Don't you run the risk of early disposing of the dc instances by encapsulating them as delegates? in the case of deferred execution the dc instance needs to be present right?
cottsak