Search code examples
entity-frameworkef-code-firstsql-server-cedesktop-application

Short-living DbContext with desktop applications and a local database


This question was inspired by an earlier question i have asked here, I have learned from that question that DbContext instances should be short living dependencies. Now given that i develop LOB desktop applications with local databases using SQL CE i have a few questions:

  1. In my case (local db, single user, desktop app), should DbContext really live for a short-period of time ?
  2. if i disposed of my DbContext with every operation, would that make me lose all the tracking information gathered through out its life cycle ?
  3. if the answer to 2 is true (trouble!), how to go about doing it the right way, should i develop a UnitOfWork that keeps change tracking information or what ?!

Solution

  • 1) Yes, short is good. But every user input/interaction is extreme

    2) Clearly yes. But beyond a logical unit of work from a Client interaction, the pattern of discarding the context fits in well. eg Change an order. Perhaps Header, Items and cust loaded. New address added to cust, Order header changed and SaveChanges. New logical interactions starts on client. Dont forget you can have several smaller contexts. Indeed bounded contexts are key to performance. Perhaps you have 1 long running context with system config and other such settings that are non volatile, few in number but accessed very often. I would keep such a context for longer.

    *3)*Not sure exactly what the question is. But a LUW type of Class that has a method Commit and then disposes the context is 1 such pattern.

    Dont forget to generate Views on DbContexts if reloaded often.