I’m working on a 2-tier WPF/EF Code First application. I did a lot of googling but couldn’t find a sample implementation of what I was looking for… was hoping that someone on this forum could help me out. Here are the requirements:
- On Application Start up
- Open a DBContext
- Cache the reference data in various maps/lists when the application starts
- Close Context.
- When user opens a form
- Open a DBContext (I’m using UnitOfWork pattern here)
- Fetch a fresh copy of Entity from context for Editing.
- Call SaveChanges() when Save button is hit.
- Close the Context.
The problem manifests when I use an object from Cache to change a navigation property.
e.g. use a drop down (backed by cache which was created using a different DBContext) to set Department navigation property.
The UnitOfWork either throws an exception saying entity was loaded in another DBContext (When Department is lazy loaded DynamicProxy) or inserts a new row in Department table.
I couldn’t find even a single example where reference data was being cached… I can’t believe that no one came across this issue. Either I’m not looking in the right place or not using the right keywords.
I hope this is doable using EF. I’d appreciate if you can share your experiences or post some references.
I’m kinda new to this so would like to avoid using too many frameworks and just stick to POCO with WPF/EF stack.
I ended up defining int foreign key property in addition to navigation.
In my application I only modify the int property and use the navigation property for displaying the details (read only controls).
While this works it makes the application a little fragile and sometimes inconsistent.
although this blog claims that the FK & Navi properties are synced by EF but I couldn’t get it to work.
http://coding.abel.nu/2012/03/ef-code-first-navigation-properties-and-foreign-keys