MVVM and ORM tools - wpf

I am confused.Please guide me anyone.
Is it mandatory to use any ORM tools(EF or Linq2SQL) when building an application in MVVM pattern?
Right now my application returns dataset using straight queries to like "select * from table"
Can I use dataset/datatable to List and then observable collection?or we need to have EF or L2S.
I am confused to kick start in MVVM

There's no reason you can't build your own Model layer, if that's what you want to do. The nice thing about modern design patterns is that they are generally agnostic toward what you use to fill each part.
I would build specific, separated classes for all your data access code, to keep that first M separate.
An overarching principle of patterns like MVVM and MVC are to separate your various concerns. This helps in so many ways - including, specifically, to support your ability to use your own data access (Model) while using the general pattern.
Ideally, you would write your code such that if you decided to move to Entity Framework in the future, you could do so without much change in the rest of the code. Rather - without any change in the rest of the code.
You can write your data access using the Repository pattern, using your custom classes that execute your hand-written SQL and produce classes that your View and ViewModel can deal with. With the Repository being the main place where your other code interacts, if you switch to EF or anything else in the future, you know you don't have to change any of your View or ViewModel code.

Related

What is the real purpose of ViewModel in MVVM?

I had a talk with teamlead about this topic and from his point of view we can just use bindings and commandings omitting ViewModel, because we can test UI behaviour without VM using Automation or our own developed mechanisms of UI testing (based on automated clicks on Views). So, if there are no real benefits, why should I spawn "redundant" entities? Besides, automated integration tests look much more indicative than VM tests. So, it seems that we can mix VMs and Models.
update:
I agree that mixing VMs and Models brings into single .cs a data model and rules of data transformation for representing it in a View. But if this is only one benefit - I don't want to create a VM for each View.
So what pros of VM do you know?
The VM is the logic behind your UI. combining the UI code with the logic ends up in a mess, at least from my experience. Your view should define what you see - buttons, menus etc. Your VM is in charge of the binding and handling events caused by the user.
Edit:
Not wanting to create a VM for each view doesn't sound like a SW-oriented reason. Doing so will leave your view clean of logic and your model free to be the connecting layer between the core layer and your app layer.
I like the following example referring to the model and its role (why it shouldn't be combined with the VM): imagine you're developing some Android app using Google maps. Google maps are your core. Then one fine day you really need the option to, say, color parts of the map in pink, bright pink. An email to Google asking for colorPink(Map)will probably get you nowhere. That's where your model steps in and provides you the map wrapper that you need to define your pinky method.
Without a separate model, you'd have to go through every VM that uses map and update it.
So, the view has a role, the model has a role, the VM is the logic between those.
Edit 2:
There are some cases where there's no need of a model layer - I tended to disagree at first but was convinced after a discussion: In relatively small applications, the model can end up being a redundant wrapper with no added functionality over the core. In such cases, you can use the core objects directly.
What is he binding to? Whatever he is binding to is effectively a view model, whether you call it that or not. If it also doubles as a data model, then you're violating the Single Responsibility Principal (SRP). Essentially, the problem here is that you're lumping together code that is servicing different parts of the application architecture, which will lead to a convoluted mess.
UI Testing is a pain not just because you need to accomodate for changes in the View which can occur many times but also because UI tends to interfere with its own testing. Depending on the tests needed you'll need to keep track of focus, resize and possibly other (mouse) events which can be extremely hard to make it a representative test.
It is much easier to scope the test to the logic in the ViewModel and leave the UI testing to humans. The human testers do not need to test the logic; their only consern should be the UI.
By breaking down a ViewModel into a hierarchy of ViewModels you might be able to reuse a ViewModel multiple times. There is no rule that states that you should have a ViewModel for each View. (After a release or two I end up there but that's besides the point :) )
It depends on the nature of your Model - sometimes they are simple and can serve as both like you are suggesting. However, depending on the framework, you'll need to dirty up your model with some PropertyChanged event code which can get messy and distracting. In more complex cases, they serve as a mediator between your the view and the model. Let's suppose you're creating a client app that monitors a remote process or database entries - creating View Model's for these entities let's you surface your data in a way that is convenient to bind to for a UI framework (but is silly in a DB framework), encapsulate operations as commands, perform validation, etc etc.

Entity Framework 4 - lifespan/scope of context in a winform application

Sorry for yet another question about EF4 context lifespan, but I've been wondering about this for a while and I do not seem to find the answer. I'm not very familiar with lots of patterns or overcomplicated stuff (in my point of view) so I want to keep it simple.
I work with an ASP.NET application where the context is managed by each http request which is a very good approach in my opinion.
However I'm now working with a winforms application and I sometimes have transactions or reports that will not perform very well if I simply create the context for each query. Not that this performance issue is a very problematic thing, I just want to hear if there's a simple strategy as per HTTP request in ASP.NET for winforms?
Don't create a context for each query. At the same time, don't create a context that gets used for the entire lifetime of a Form (or your application).
Create a context for a single Unit of Work (which can encompass many queries).
That way you have all of your changes encapsulated in the context and you let Entity Framework wrap the database calls in a pretty little transaction without having to worry about it yourself.
I prefer to abstract the Repository and Unit of Work patterns out of the Entity Context so that I can use them independently (which makes everything very clear). MSDN actually has a decent article on the details:
MSDN - Using Repository and Unit of Work patterns with Entity Framework 4

MVVM with WPF using LINQtoSQL in a DAL along with a BLL

My goal is to have an app that is using WPF and is a 3 tier architecture. UI, BLL, and DAL...I'd like to use the MVVM but I'm not sure how that works with a 3 tier architecture or if it is something entirely different. So with that in mind, I have a few questions:
1) LINQtoSQL: I've read a lot online that say LINQ replaces your DAL and seen many articles that say this a bad idea. I'm thinking it's a bad idea, however, what do I put in here? What are the datatypes i am returning to the BLL? IQueryable? ObservableCollection? I have no clue.
2) The BLL: I'd like to make this a service that runs on a server, so that when I need to make a change I don't need to redeploy the whole app, I just need to restart the service. But, I'm not sure where to start on this.
3) With the BLL, I guess I'm confused on how the data is going through all the layers from the DAL all the way to the Interface.
I've done lots of research online, and have got bits and pieces of things, however I haven't seen anyone talk about a WPF application that is using MVVM with LINQ in the DAL using SQLMetal and a BLL thats running on a server. Can anyone point me in the right direction? or maybe a book to get?
Mike,
your question is really cool, I like it. Firstly, feel free to experiment a bit - each and every project is different, so there's no single rule, which fits everywhere. That's why I would suggest just leaving DAL to LINQ 2 SQL. this great tool will handle it, you don't have to worry. Secondly - you mentioned 3 Tier Architecture, but why isn't there place for the Model? Since all models are generated automatically (e.g. SQLMetal), you don't have to worry about mappings either. So, if you're not bored yet, let me answer all of your 3 questions:
Skip DAL and observe your project carefuly - if you have a feeling, that it's lacking this layer - add it (it will contain LINQ2SQL queries). And the second part - you can return whatever you wish, but it will be most convenient for you to use IEnumerable<> or IQueryable<> parametrized with your models.
My intuition tells me, that you're going to need WCF - in this case you should be able to wrap whole (yes, that's true) whole business logic in a nice Contract and implement however you wish.
This is the easiest one :) Since your BLL layer is actually an implementation of some Contract (Interface), you can design that Interface to provide you with all data you need. For example:
Contract/Interface:
IEnumerable<User> GetTallUsersOver40();
IEnumerable<User> GetShortUsersOver60();
...
And that 'all the layers' you were talking about shrink to a single LINQ2SQL query execution. If you need more logic - place it in this layer.
I want to use MVVM, what now? The answer is simpler than you think - just prepare your views and view models and simply consume your BLL Contract/Interface implementaion.
Please ask if you have further questions!
I'll try to provide some insight, though I'm not an expert, I've tackled these issues in the past.
LINQ to SQL is actually pretty good at what it's supposed to do - which is replace your DAL. But don't return an IQueriable upwards to your BLL, as that would enable (or at least hint to the possibility) the BLL to query your DB directly. You should transfer the data object to the BLL and let it construct a matching business object. Also note: LINQ in and of itself can be used in any layer (and in fact is one of the best features of C#). LINQ to SQL is the mechanism by which LINQ statements get transated to SQL queries.
BLL as a service is a natural choice. Provide an upward interface to the presentation layer (a WCF service is a good option here).
The BLL generates business objects based on data it receives from the DAL. In order to provide for good decoupling of layers, you should use different classes for your DAL and BLL objects. Don't create a dependency between your presentation layer and your data layer.
Great question. I don't think there is any one place that has all the answers. I had very similar questions when we were starting a new project. MVVM is really just a presentation pattern and doesn't care of all the details like you listed. Laurent Bugnion has a good framework that glues everything together as well.
LINQ2SQL is cool but can get cumbersome with the VS08 designers. Take a look at http://plinqo.com/ to use with CodeSmith to generate the DAL and I think it will even do the BLL with contracts as well. Another generating option is Oleg Sych T4 templates One issue we ran into with LINQ2SQL is the singular datacontext. If you don't need to be modular this isn't an issue.
I agree with what the others said about data contracts and look at what Plinqo can generate. It may save you a lot of time.
The data will work it's way up in objects usually. Like the others said make sure you keep a seem between all the layers so you don't have dependencies.
When you get to the MVVM part you will open a whole new can of worms. I don't think there are many or any books out on MVVM yet. It is still a somewhat new fad.
Great question, I'm on the nursery slopes of the WCF/WPF learning curve so I'm in a similar position to you. My 2 cents:
Haven't got into Linq to SQL, I'm old school and used to writing stored procedures and views. I'm currently using these to populate DTO classes - that is, classes with no methods, just properties to represent the data. I know I'm probably behind the curve on this.
Make your BLL a WCF service - put the service contract(s) and data contract(s) in their own assembly, you can then include this in your client, where they become your model, or part of it.
In your client application, include a reference to the assembly containing the service contracts and data contracts. The data contracts then become your model, your ViewModels can wrap these models and expose their properties (implement INotifyPropertyChanged for databinding).
I'm using the O'Reilly books Programming WCF Services, Learning WCF Services and Programming WPF which I'm finding pretty good. I don't know of any books specifically about MVVM but there's loads of stuff on the web.

Using Linq-to-SQL entities in your BLL or UI?

I had a client ask for advice building a simple WPF LOB application the other day. They basically want a CRUD application for a database, with main purpose being as a WPF training project.
I also showed them Linq To SQL and they were impressed.
I then explained its probably not a good idea to use that L2S entities directly from their BLL or UI code. They should consider something like a Repository pattern instead.
At which point I could already feel the over-engineering alarm bells going off in their heads (and also in mine to some extent). Do they really need all that complexity for a simple CRUD application? (OK, its effectively functioning as a WPF training project for them but lets pretend it turns into a "real" app).
Do you ever think its acceptable to use L2S entities all through your application?
How difficult is it (from experience) to refactor to use another persistence framework later?
The way I see it, if the UI layer uses the L2S entities as a simple a POCO (without touching any L2S specific methods) then that should be really easy to refactor later on if need be.
They do need a way to centralize the L2S queries, so some sort of way to manage that is needed, even if they do use L2S entities directly. So in a way we are already pushing toward some aspects of DAL/DAO/Repository.
The main problem with Repo I can see is the pain of mapping between L2S entities and some domain model. And is it really worth it? You get quite a lot "for free" on L2S entities which I think would be hard to use once you map to another model.
Thoughts?
The only major drawback to using L2S entities all the way through is that your UI needs to know about and bind to the concrete entities. That means your UI knows your data layer. Not usually a good idea. You really want a layered approach for anything that has the potential to be serious.
That said, it's perfectly possible to use the LINQ-to-SQL entities themselves in a layered architecture without knowledge of the data layer: extract interfaces for the entities and bind to them instead.
Keep in mind that all L2S entities are partial classes. Create interfaces that reflect your entities (Refactor => Extract Interface is your friend here) and create partial class definitions of your entities that implement the interfaces. Put the interfaces themselves (and only the interfaces) in a separate .DLL that your UI and Business Layer reference. Have your Business Layer and Data Layer accept and emit these interfaces rather than the concrete versions of them. You can even have the interfaces implement INotifyPropertyChanging, since the L2S entities themselves implement those interfaces. And it all works peachy.
Then, when/if you need a different persistence framework, you have no pain at all in the BL or UI, only in the data layer -- which is where you want it.
Repositories are not a big deal. See here for a pretty good treatment of their use in ASP.NET MVC:
http://nerddinnerbook.s3.amazonaws.com/Part3.htm
Basically what we did for a project was that we had a Business layer that did all of the "LINQing" to L2S objects... in essence centralizing all querying to one layer via "Manager Objects" (I guess these are somewhat akin to repositories).
We did not use DTOs to map to L2S; as we didn't feel is was worth the effort in this project. Part of our logic was that as more and more ORMs support Iqueryable and similar syntax to L2S (e.g. entity framework), then it probably wouldn't be THAT bad to switch to a different ORM, so its not that bad of a sin, IMO.
Do you ever think its acceptable to use L2S entities all through your application?
That depends. If you do a short lived product you can get things easily wired up in a quick succession if you use L2S. But if you do a long lived product which you might have to maintain for a long duration, then you better think about a proper persistence layer.
How difficult is it (from experience) to refactor to use another persistence framework later?
If you use L2S in all your layers, well then you must not think about re-factoring them to use another persistence framework. This is exactly the advantage of using a framework like NHibernate or Entity Framework in your persistence layer , that though it requires a bit of extra effort upfront it will be easy to maintain in the long run
It sounds like you should be considering the ViewModel Pattern for WPF
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

MVVM with XML Model and LinqToXml?

I've been reading up on the MVVM pattern, and I would like to try it out on a relatively small WPF project. The application will be single-user. Both input and output data will be stored in a "relational" XML file. A schema (XSD file) with Keys and KeyRefs is used to validate the file.
I have also started to get my feet wet with Linq and LinqToXml, and I have written a couple pretty complex queries that actually work (small victories :)).
Now, I'm trying to put it all together, and I'm finding that I'm a little bit confused as to what should go in the Model versus the ViewModel. Here are the options I've been wrestling with so far:
Should I consider the Model the XML file itself and place all the LinqToXml queries in the ViewModel? In other words, not even write a class called Model?
Should I write a Model that is just a simple wrapper for the XML file and XSD Schema Set and performs validation, saves changes, etc.?
Should I put "basic" queries in the Model and "view-specific" queries in the ViewModel? And if so, where should I draw the line between these two categories?
I realize there is not necessarily a "right" answer to this question...I'm just looking for advice and pros/cons, and if anyone is aware of a code example for a similar scenario, that would be great.
Thanks,
-Dan
For a small application, having separate Data Access, Domain Model and Presentation Model layers may seem like overkill, but modeling your application like that will help you decide what goes where. Even if you don't want to decompose your application into three disitinct projects/libraries, thinking about where each piece of functionality should go can help you decide.
In that light, pure data access (i.e. loading the XML files, querying and updating them) belongs in the data access layer, since these are technology specific.
If you have any operations that don't relate to your particular data access technology, but could rather be deemed universally applicable within your application domain, these should go into the Domain Model (or what some call the Business Logic).
Any logic whose sole purpose is to provide specific functionality for a particular user interface technology (WPF, in your case) should go into the Presentation Model.
In your case, the XML files and all the LINQ to XML queries belong in the Data Access Layer.
To utilize MVVM, you will need to create a ViewModel for each View that you want to have in your application.
From your question, it is unclear to me whether you have anything that could be considered Domain Model, but stuff like validation is a good candidate. Such functionality should go into the Domain Model. No classes in the Domain Model should be directly bound to a View. Rather, it is the ViewModel's responsibility to translate between the Domain Model and the View.
All the WPF-specific stuff should go in the ViewModel, while the other classes in your application should be unaware of WPF.
Scott Hanselmen has a podcast that goes over this very topic in detail with Ian Griffiths, an individual who is extremely knowledgeable about WPF, and who co-wrote an O'Reilly book titled, "Programming WPF."
Windows Presentation Foundation explained by Ian Griffiths
http://hanselminutes.com/default.aspx?showID=184
The short (woefully incomplete) answer is that the view contains visual objects and minimal logic for manipulating them, while the View Model contains the state of those objects.
But listen to the podcast. Ian says it better than I can.

Resources