I have a VB WinForms project, and we use Entity Framework 6 code-first. I know that in web apps it's ideal to limit the lifetime of dbContexts (which we use indirectly through repository classes), but I learned recently that you're supposed to keep a dbContext around for the lifetime of a form, generally, for WinForms projects.
So let's say I have class ClassA and class ClassB, and all ClassA objects have an optional ClassB object (and related "ClassBId" properties for EF6 to use as a foreign key). We have a form, ClassAForm, for users to edit and view ClassA objects, and this naturally displays a little info about its ClassB object; this ClassB should be exclusive to the ClassA, but might also be viewed on other forms. There is a button on this form to open another form, ClassBForm, that allows users to edit and view ClassB objects. ClassBForm isn't modal, and doesn't currently pass anything to the ClassAForm that spawned it, although ClassAForm does have listeners for events in ClassBForm.
So from my understanding, ClassAForm would get its own long-lived dbContext object that it retains for the form lifetime; ClassBForm would get its own dbContext object. So if I make changes to the ClassB object in ClassBForm's dbContext, what is the ideal way to see those changes in ClassAForm's dbContext's version of that ClassB object, where the ClassB is likely a navigation property of a ClassA?
I can think of a few solutions to this problem but I'm not sure what is the best practice; it's also possible (and I hope someone will mention it) that my entire understanding or framing is incorrect.
(Possible) Solutions I've thought of:
- Ignore the MS advice, and only keep dbContexts alive for specific DB interactions; refresh the dbContext(s) on every update event and form load, like it's a web app
- Pass the same dbContext(s) from form to form (in the constructor of my repository classes, in my case) and only dispose it rarely (not ideal- database gets updated by a couple of services)
- Manually attach/detach and mark updates as updated in my data layer
- Pass the updated objects by event to other forms, and update the objects manually in each context (I assume this would run into trouble when I need to save changes?)