Abstracting DbContext in WPF-Prism - wpf

Trying to build a single user Desktop application using
WPF as the UI
Prism for MVVM and other frills
Unity being the preferred DI
Entity Framework as the preferred ORM
I've read about using EF in desktop scenario as above and guess the following are the two possible ways of going about it...
Use the DbContext in the ViewModel directly (ties you to EF permanently)
Use the DbContext in the ViewModel via DI (abstraction)
I prefer the second approach, and tried the following path.
Use Interface and Implementation classes that abstract DbContext
Create a Service Layer that uses the above
But now, I'm afraid I've lost all the cool change tracking that EF offers and my models are on their own to track their state and inform the DbContext of their state when reattached to it...
While its ok in a web app with WCF services and all... it seems overkill to enable my model with change tracking, for a simple single user desktop application...
Do I make any sense here? Am I getting anything wrong or missing something.
Need help, thanks in advance.
Cheers.

Related

Implement MVVM With Entity Framework

I created database in management studio, a model in my project with the ADO.NET Entity Data model for the tables.
I want to use the MVVM pattern to build forms and update, delete, insert data in my forms.
Can you please give me some guidance how to map the models with my viewmodels. Any tutorials would be nice, I`ve already spend whole day looking for something but got confused at the end.
Is there a simple project with Entity Framework and MVVM.
This is a bit of a contentious subject but I personally don't view change notification as belonging in the exclusive domain of the view/view-model relationship, so I add INPC to my models as as well and expose them in their corresponding view model. This can be done by either injecting proxies into your repositories at runtime (e.g. Castle Dynamic Proxy) or by modifying the IL automatically at compile time (e.g. Fody).
From one noob to another - try searching for 'wpf mvvm entity framework example'. Here's what I found useful...
http://www.software-architects.com/devblog/2010/09/10/MVVM-Tutorial-from-Start-to-Finishhttp://social.technet.microsoft.com/wiki/contents/articles/28209.wpf-entity-framework-mvvm-walk-through-1.aspx
First you can use the repository pattern, to abstract your data access layer, so you viewmodels don't have a tight coupling to Entity Framework and remain easy to test.
Second, you can use an auto mapper like AutoMapper to map from your models to your ViewModels. However, you shouldn't use automappers to map from ViewModels to the View, so you'll have to manually create your model and pass it to your repository for insertion or updating.

Connect NHibernate with the MVVM Light Toolkit

I have the following problem:
In my Application I have to connect to an Access Database - yeah, I know that Access isn't a great database - but I have to use it.
The Application will be written in WPF, with the MVVM Light Toolkit and "NHibernate".
How do I connect "NHibernate" with the MVVM Light Toolkit?
Do I use the Hibernate Entities as "MVVM" Models?
And what's the best place to store user settings which are only need on runtime?
how do i connect "NHibernate" with the MVVM Light Toolkit?
Given the Three Layer Architecture, you should differ your GUI from you Database layer.
This means that you shouldn't tie your MVVM framework and your ORM framework together.
Among many other disadvantages that this binding will have, it will create high coupling between your GUI and DB, and make it extremely hard to replace, if oneday you'll want to change some of those frameworks.
Do i use the Hibernate Entities as "MVVM" Models
The ultimate loose coupling will be to create a different assembly to store your entities, which you can reference both from you GUI, where they will act as "MVVM" Models, and from your DAL, where they will act as NHibernate Entities.
what's the best place to store user settings which are only need on runtime?
The best place to store user settings are in the App.config file under the <userSettings> tag, which you can also do from the .Settings file under the User scope.
You can easily access them :
var mySetting = Settings.Default.mySetting;
If you want settings that will be available only as the application's lifetime, you can create properties in a static class to hold your settings:
public static class UserSettings
{
public static string MySetting { get; set; }
}
Hope this helps
Maybe read this article to get started with the MVVM pattern.
No you would not use the nHibernate entities as ViewModels in you application otherwise you would have a MVM pattern or something like this ;)
It's usually not a good idea to use entities as models exposed to the front end directly because you would mix up data and UI layer...

Input Validation in Silverlight 4 to EF Entity

I have a Silverlight application that is loading Entities from a WCF Service via DataBinding.
So I have several views with many textboxes whose textboxes contents are binded to a Entity properties.
I want to use Silverlight validation and I don't want to use the exceptions way (I have some entities with a lot of properties... and I don't want to repeat it every time I use it in a form...).
So I'm triying to use the IDataErrorInfo way, but I'm not sure how should I do it.
I think I should declare a client-side model with equivalent classes to the Service EF Model but implementing the IDataErrorInfo. This solution means duplicate the model code and make any way to translate from service model to client model.
The other solution could be to change the EF Model itself but I don't know if this is correct for the MVVM (this is really near to the view, isn't it).
Maybe there is another magical solution I don't know.
Any suggestions??
The recommended interface is actually INotifyDataErrorInfo
Which gives you a little more control and supports multiple errors. It's also a little bit easier to use in scenarios when you manually want to control when validation happens.
Basically, with this, you could create a validate method on your "client side" objects which goes through their properties, validates each one, and builds up a list of errors. (HasErrors becomes true, you notify ErrorsChanged and then the code that binds to your object does GetErrors.
With this way, you could build a validation engine and have each EF object poll your database for validation rules.
There's also this: http://msdn.microsoft.com/en-us/magazine/ee335695.aspx
If you have the option of annotating your EF classes on the client side instead of simply using the generated ones, you may be able to find an easy solution here.
I know this is slightly off-topic since you're using WCF
but if you were to use RIA Services, then it generates objects from your EF, and you can simply add some attributes to them in the RIA (it comes with comments telling you which attributes to use)
and it's very very simple.
but that advice is relevant only if you were to use RIA.

Silverlight 4 WCF RIA Services and MVVM is not as simple

[Disclaimer: I'm ASP.NET MVC Developer]
Hi,
I'm looking for some best practices with implementing MVVM pattern with WCF RIA in Silverlight 4.
I'm not looking to use MEF of IoC for locating my ViewModels. What I would like to know is how to apply MVVM pattern with Silverlight 4 and WCF RIA.
I don't want to use other stuff like Prism or MVVM Light toolkit. I found many examples on Internet showing how it is wonderful to drag and drop a datasource on the view and the job is done (it reminds me about my first VB6 developments).
I tried to implement MVVM with WCF RIA and it's not strightforward at all. If I understand, the MVVM should contain all the logic in order to unit test it in isolation but when it comes to combine it with WCF RIA it's another story. I have the following questions.
Can I use a generated metadata as model ? It would be easier to use it that if I write all from the scratch.
As I saw the only way I could get data is through DomainContext or through direct binding in the view (local ressource). I don't want the direct binding in the view, not testable at all. On the other hand I can't use DomainContext, it doesn't expose any single entity !!! All I have is the EntitySet that I can bind to datagrid. How do I bind a single Entity to the DataForm from the ViewModel ?
How do I udpate the model to the database ?
How do I navigate from one Entity to a collection of it's items. For example if I have a Company Entity I would like to show a DataForm to update an entity informations and a datagrid to show companies adresses. When saving a form, I would like to save an information to Company and an information to adress about which adress was selected as active.
Please help me understand how to do it well. Or maybe I should drop the WCF RIA and to do it with WCF from scratch ?
What do you think ?
You might be interested in this session. It explains how to use the MVVM pattern with RIA WCF Services.
I found this post useful:
http://www.astaticstate.com/2010/04/silverlight-4-using-mvvm-patter-ria.html
Some random answers...
I don't think that MEF is particuarly well suited for Silverlight. It's primarily for desktop apps, and could be adapted for other uses where the plug-ins are in the local file system relative to the app.
MVVM requires that you understand roles. The "view" is your XAML and code-behind. The code-behind should handle events from the user control, but very little more than that.
The ViewModel holds the data that the user control will bind to. Generally, the ViewModel is bound to the View as its DataContext, so that everything in the form can databind to properties in the ViewModel. The ViewModel must implement INotifyPropertyChanged, and raise property changed events for every property that the form databinds to.
You'll probably want to create an ObservableCollection, using an EntitySet as your source. This will handle INotifyCollectionChanged for databinding purposes. If the entities in the EntitySet also handle INotifyPropertyChanged, then you're in good shape on databinding for collections.
You can create a property for an individual entity, and databind to that, assuming that change notification is also implemented (both for entity members, and for the entity property).
RIA Services will regenerate the DomainContext on each build, which helps a little in keeping it in sync. It's intended to be a service layer above an ORM, though, so your ORM or other data mapping will still have to be maintained by other means.
I haven't looked at the final release of RIA Services, but I wasn't hugely impressed with the beta version. I'd rather have good entity classes defined on the server, and share them with the Silverlight project. It's not easy to set up, though, and requires some non-trivial WCF that doesn't rely on service referernces. (RIA Services final release may have cleaned some of this up, but the native WCF service reference in Silverlight is pretty much evil, mainly because it doesn't automatically recreate generated classes, and it hard-codes the URI for the server-side service.)
Metadata was another problem with RIA Services beta. It's easier to attach metadata attributes directly to your DataContract class and the individual DataMember properties, if you control the entity source. Again, that may mean not using RIA Services. Writing a separate metadata class, as was required for the RIA beta, wasn't a good solution.
I ended up not using RIA Services for Silverlight 3, and didn't regret it. Here's an excellent article on WCF and Silverlight. Although it says Silverlight 2, it's still on-target for any Silverlight release.
I do recommend MVVM Light. Source is available on Codeplex, if that's an issue. It provides messaging and commanding support, as well as a ViewModelLocator; while the latter takes a bit of work to understand, it's really a good extension to the basic MVVM model.
Hope this helps.....
Just thought I would let you know about a project I am working on - just got our first release done. Provides a great simple way to approach MVVM for Silverlight + RIA Services specifically. Simplifies a lot of the MVVM stuff, and provides some more controller-like functions with the Notifications class. http://slmvvms.codeplex.com/

How would you implement MVC in a Windows Forms application?

I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development.
Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?
What I've done in the past is use something similar, Model-View-Presenter.
[NOTE: This article used to be available on the web. To see it now, you'll need to download the CHM, and then view the file properties and click Unblock. Then you can open the CHM and find the article. Thanks a million, Microsoft! sigh]
The form is the view, and I have an IView interface for it. All the processing happens in the presenter, which is just a class. The form creates a new presenter, and passes itself as the presenter's IView. This way for testing you can pass in a fake IView instead, and then send commands to it from the presenter and detect the results.
If I were to use a full-fledged Model-View-Controller, I guess I'd do it this way:
The form is the view. It sends commands to the model, raises events which the controller can subscribe to, and subscribes to events from the model.
The controller is a class that subscribes to the view's events and sends commands to the view and to the model.
The model raises events that the view subscribes to.
This would fit with the classic MVC diagram. The biggest disadvantage is that with events, it can be hard to tell who's subscribing to what. The MVP pattern uses methods instead of events (at least the way I've implemented it). When the form/view raises an event (e.g. someButton.Click), the form simply calls a method on the presenter to run the logic for it. The view and model don't have any direct connection at all; they both have to go through the presenter.
Well, actually Windows Forms implements a "free-style" version of MVC, much like some movies implement some crappy "free-style" interpretation of some classic books (Romeo & Juliet come to mind).
I'm not saying Windows Forms' implementation is bad, it's just... different.
If you use Windows Forms and proper OOP techniques, and maybe an ORM like EntitySpaces for your database access, then you could say that:
The ORM/OOP infrastructure is the Model
The Forms are the Views
The event handlers are the Controller
Although having both View and Controller represented by the same object make separating code from representation way more difficult (there's no easy way to plug-in a "GTK+ view" in a class derived from Microsoft.Windows.Forms.Form).
What you can do, if you are careful enough. Is keep your form code completely separate from your controller/model code by only writing GUI related stuff in the event handlers, and all other business logic in a separate class. In that case, if you ever wanted to use GTK+ to write another View layer, you would only need to rewrite the GUI code.
Windows Forms isn't designed from the ground up to use MVC. You have two options.
First, you can roll your own implementation of MVC.
Second, you can use an MVC framework designed for Windows Forms.
The first is simple to start doing, but the further in you get, the more complex it is. I'd suggest looking for a good, preexisting and well-tested, MVC framework designed to work with Windows Forms. I believe this blog post is a decent starting point.
For anybody starting out, I'd suggest skipping Windows Forms and developing against WPF, if you have the option. It's a much better framework for creating the UI. There are many MVC frameworks being developed for WPF, including this one and that one.
According to Microsoft, the UIP Application Block mentioned by #jasonbunting is "archived." Instead, look at the Smart Client Application Block or the even newer Smart Client Software Factory, which supports both WinForms and WPF SmartParts.
Check into the User Interface Process (UIP) Application Block. I don't know much about it but looked at it a few years ago. There may be newer versions, check around.
"The UIP Application Block is based on the model-view-controller (MVC) pattern."
Take a look at the MS Patterns and Practices Smart Client application block which has some guidance and classes which walk you through implementing a model view presenter patter in windows forms - take a look at the reference application included.
For WPF this is being superseced by the prism project
The software factories approach is a great way to learn best practices

Resources