Using Entity Framework with repository pattern in WinForms MDI - winforms

We are about to start up a new project similar to a previous one. I could just copy the old design but I am not all too satisified with the old design.
It is a "standard" business system (sales,stocktaking,warehousing etc) built ontop of .Net 3.5 (Winforms MDI) with Entity Framework in the backend.
All forms inherit from a baseform (which inherits Windows.Form). The form exposes a property called ObjectContext, which on the first call instantiates a new ObjectContext. This makes up a pretty good UnitOfWork i think, having all data-access isolated in each form.
However.
I have encapsulated all queries and common CRUD in "poor mans repositories". These Repositories are exposed as properties of the ObjectContext.
So if I wanted to bind and order to a form I would call
OrderLinesGrid = ObjectContext.OrderRepository.GetOrderLinesByID(orderID).
The OrderRepository gets a reference to the objectcontext created for the form, like this
(In my partial ObjectContext class)
Private _OrderRepository as OrderRepository
Public ReadOnly Property OrderRepository as OrderRepository
Get
if _orderrepository is nothing then
_orderrepository = New OrderRepository(me)
end if
return _orderrepository
End Get
End Property
What I do not like about this is:
The call to the repository is made
through ObjectContext. Hence, I do
not get abstraction between the
query and the dataaccesslayer I
would like.
For each new type in my Domain I
need to create a property in my
ObjectContext
My call to OrderRepository should just return domain objects and not worry about how it is persisted. Also, I cannot have each Repository have it's own ObjectContext since that would require me to Attach and Detach objects when referencing i.e Country to a Order.Country property.
I would appreciate any ideas and feedback on this design :)

I suggest you research "onion" principle , Repository pattern and Luw pattern.
There are many examples on the web.
Essentially you use POCO Model Core Project. No references to DAL project.
You declare interfaces for the Repository and luw patterns in the CORE project.
So Now a
UI layer -> instantiate context and DAL Object eg repository -> inject into CORE services.
Also connected to this approach is Inversion of Control or dependency injection pattern.
If you use test driven development against Dummy Repositories you can make sure the design principles are adhered to.

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...

WPF project - Entity Framework Injection vs Application Property

I am very new to WPF.
I am trying to figure out pros/cons of various architecture patterns in WPF, while creating an application designed to interact with a database.
The application begins with a master window, which contains various buttons which load other windows which each perform CRUD operations on different tables within that DB.
I am wondering about the merits and disadvantages of 3 possible approaches:
1) Instantiate a new entity instance within the constructor for each window
2) Each window have a have a constructor which supports dependency injection of the entity object. Every time the master window instantiates a new window object, it injects its own instance of the entity.
3) As per WPF Data Binding Walkthrough Create public ObjectResult properties on a class which inherits from application, and link to this/these properties in the
<Window.Resources><CollectionViewSource>
Tag of the various windows.
Thanks
Dependency Injection is the best option giving you most flexibility...
However, you shouldn't inject something as specific as the entity object but some service provider instead which would be a specific implementation of a service Interface and would not use the entity object directly but a Model instead which would abstract away the data access specifics giving you loose coupling benefits...

How does EF work in WPF/Silverlight apps?

I've been trying for a while to wrap my mind around 2 concepts at once, learning MVVM (and one of the hard things has been trying to figure out which framework to use. We didn't even know how many there were until a few weeks ago) and also I'm trying to learn Entity Framework 4.2.
This is for a WPF app that we're going to be writing.
I've gotten Julia Lerman's book and I'm also going through an online training course on EF, but one thing I still don't get, and haven't seen any example of yet, is how to handle something like the INotifyPropertyChanged interface with the classes created via EF, regardless of whether we use MVVM or not, working with INotifyPropertyChanged is vital.
So, let me ask here the plain question:
Do you allow EF to create all of the data access classes that reflect all of the data in your database, and then duplicate much of that code so I can get it to work with INotifyPropertyChanged? Or is there some other way of doing that?
I was baffled when the thought came to me, that I'd have to map every data object to a new one only implementing INPC on top of it.
Then I found a trick: assuming you're going to use WCF, it automatically implements INPC.
For the collections, just go into the Service Reference configuration, and set it so that it gives you ObservableCollection as default collection type.
That's it, you're set for MVVM =)
Because the ViewModel is created with the needs of the View in mind, only in very simply cases the ViewModel and your Entity are the same class. Normally you have an Entity class and a ViewModel class.
INotifyPropertyChanged is only one of the reasons for this. There are others like conversions, validation, meaningful error messages, aggregation etc.
I have previously used Entity Framework in several of my WPF applications. The first time I used EF Database first. It was pretty tricky to get the model exactly the way I wanted it, and once it was working, then I had to go through and implement INotifyPropertyChanged on my entity classes.
Recently, I have started using EntityFramework CodeFirst with 4.1, I have found it is much much easier to handle all of the property changed stuff. I generally create a base class with INotifyPropertyChanged implemented on it and inherit my entities from that.
As far as the ViewModel, I also started out worrying about this framework or that framework. Later I decided to just roll my own. Sure, the frameworks have some interesting capabilities, but for learning, I found it much easier to get into it by creating my own ViewModelBase class and inheriting all of my ViewModels from that.
ViewModelBase typically implements INotifyPropertyChanged. Later I created a ViewModel monitor class which would have a collection of ViewModels. To look them up, I gave ViewModelBase a FriendlyName property so that each type of inherited ViewModel could have a name set for it (my types are typically RecordMaintenanceViewModel, NavigationViewModel, ShellViewModel, etc) and I generally will inherit my used view-specific ViewModels from those. So on the ShipmentView in my shipping program, The ShipmentViewModel is inherited from a CollectionViewModel, which is inherited from the ViewModelBase. In this way I have functionality divided up into discreet sections allowing me to handle specific scenarios.
I generally port my ViewModel base over to every project, and often take my middle ViewModels; sometimes I have to recreate them though.

Is there any reason to make POCOs into Model objects?

If I am generating POCO objects from EntityFramework, and using these to go to/from the WCF server, is there any reason to create client-side Models for the Views & ViewModels to use instead of just using the POCOs directly?
Almost all the MVVM examples I have looked at bind straight to the object returned from the WCF service. Is this good practice? Are there arguments that can be made for actually mapping the POCO to a Model and having the Views/ViewModels working with the Model object instead of the POCO?
The main reason I could think of is validation, however since the EF POCOs are partial classes, they can be expanded on to include validation.
EDIT
Most answers so far have brought up INotifyPropertyChanged as the main reason to build a separate Model. Does your answer change if you are using Self-Tracking entities instead of POCOs which already includes INotifyPropertyChanged? STEs are also partial classes which can be expanded upon to include validation.
Validation is the main reason not to bind directly to a POCO. In addition, if the POCO doesn't already implement INotifyPropertyChanged and other required interfaces, the experience working with the object on the WPF side may be less desirable, and implementing a ViewModel to wrap this makes sense.
Providing a ViewModel to wrap your POCO allows you to encapsulate the logic into ICommand implementations as well as implement required interfaces cleanly.
I disagree only slightly with Reed (an unusual circumstance to be sure). I would NOT implement a ViewModel to wrap the POCO. I would implement a Model class to wrap the POCO and expose the Models to the ViewModel via a Service layer.
The ViewModel's primary job is to appropriately present Model data to the View and react to its requests. The architecture I'm working on for this looks like so:
1 ViewModel for each View
The ViewModel calls a Data Service layer object to retrieve Model instances (not to be confused with a WCF service)
The Data Service layer issues the appropriate CRUD requests to the backend (this uses WCF, RIA, or RESTful Services for Silverlight but could be ADO.NET or EF directly for WPF).
The Data Service uses the returned POCOs to create Model objects.
Model objects wrap the POCO object and implement INotifyPropertyChanged. Model objects enforce business rules.
I'm still working through the details but I will be publishing something more concrete in the near future.
My Models accept a WCF object which exposes those properties which I wish to use in my ViewModel. I can then also extend the object as needed. My properties point to the WCF object's property and when I have to send the object back to the WCF service, I don't have to do any more work. The models inherit INotifyPropertyChanged and INotifyDataErrorInfo which the DTOs (mentioned here as POCOs) will not have. Your business logic / validaton exists in your Silverlight application and not in your WCF Service.
The View binds to the ViewModel which has a Model (or an observable collection of Models). The Models have a WFCObject which is a DTO (mentioned here as POCO). I use my ViewModel to communicate with the service, MVVM Light has the models communicate with the service / provider - which I don't like.
Bind to EF POCOs if you want to do simple CRUD or you want to make something fast.
Otherwise, your server-side models will tend to be very closely related to the database, which changes very slowly, as compared to user interface. For less trivial UI, you'll find yourself putting more and more kludges just to fit your database model into UI (or otherwise, which is even worse).
Also, there are performance issues (e.g. would you like to transmit whole entity when for UI you need only couple of properties?), and maintenance issues (e.g. if you would like to validate premium customer's order quite differently from ordinary one).
See also http://ayende.com/Blog/archive/2010/08/06/data-access-is-contextual-a-generic-approach-will-fail.aspx
Rachel's POCO's are just dumb objects generated by EF and used for transport (DTO). Therefore, they shouldn't have other things cluttering up their domain. This is a very nice way of designing your code because it decouples any client-side requirements from those on the server-side. That's why MVVM exists - to extend the MVC model incorporating those concerns.
There is no reason you can't bind to them in your views as long as you are not modifying them directly. You can add functionality to them by adding a partial class but I wouldn't even do that. In that case you should follow the MVVM design tenants and separate those into model objects that serve your needs in the client. This will be quite automated once you hook up INotifyPropertyChanged events to notify your views.

Resources