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.
Related
I'm sorry if exactly same question is somewhere in the haystack of Stack Overflow questions but I've been searching answers for 2 days and at last I'm here.
Please feel free to mention if there are any duplicates but make sure they address the issue.
I have a very old application where code is not object oriented and sql queries are everywhere to get data and each of then uses sqlcommand/sqldatareader.
Now, I'm trying to move to WCF Web API framework and trying to separate business and data layers. Most of the sql queries return different set of columns.
I believe the sql queries must be executed in data layer.
I'm building those queries or placing existing queries in Business layer and passing those queries to Data Layer.
My plan is to return datasets from data layer. Manipulate and put into domain classes in Business layer and return into the controller.
However, I feel this is not a good approach and it's tightly coupled. I cannot find a way to how I should make it loosely coupled.
If I was to use EF or ORM then I could use DBContext to get data in the Business Layer.
I cannot map each database table to POCO class in my data layer (because most queries are complex and return different set of columns).
Question
How should I deal with the queries to make this architecture a better one in terms of making it loosely coupled?
Fixing up a brownfields project like the one you are dealing with is tricky. It sounds like you have the right idea in terms of trying to get all sql queries into a data layer.
My suggestion is to find a thin slice. A small part of the application (e.g. if the system allows you to add a user) and try to refactor the code into the structure you want. Then find the next thin slice...
Another tip is that you should do one small refactor at a time as soon as you let your refactorings get too big you increase the risk of introducing bugs.
A tool like resharper is a great help when it comes safely refactoring your code. It does have a bit of a learning curve, but it's worth the effort.
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.
I am doing something I consider to be pretty normal (although I personally haven't had to do it before), and I have assumed there'd be a 'no-brainer' way forward, but Im yet to find it - which is really frustrating.
I will be creating a WPF application, which is a data-oriented business application. My data will come from a remote IIS server (that I control) that has a standard SQL server 2008 database, so Web services/WCF seem to be the way forward. The remote service needs to be secure (reasonably) via a user (of the WPF client) username/password login.
I dont want to use 3rd party ORM products, but I expect the data layer (between the service and the database) to be able to cope with very simple ORM type functionality (I really dont want to hand-craft a data retrieval and persistence layer). Im not worried about concurrency very much as this will be a fairly simple app.
My options seem to be one of the following:
ADO.NET Entity Framework over WCF
Linq2Sql over WCF
WCF Data Services
On further investigation, none of the above seem to be the 'no brainer' Im after
1) ADO.NET entity Framework - Ive had a play with this and getting all sorts of issues serializing objects over WCF. Even when I try to generate POCO entities and use them, Im having to decorate service contracts with custom attributes just to get it to not error all the time, and I seem to have to hand-crank anything more than a flat object graph. It seems to me that EF simply isn't designed to be exposed via a service.
2) Linq2Sql - This doesn't seem much better than EF. I seem to have to hand-crank too much stuff. Ive tried the designer and SQLMetal but nothing seems to 'just work' - it all needs fiddling with.
3) WCF Data Services - this seems like a good option on the face of it, but essentially it seems like I'm just exposing my SQL database tables 'in the raw' over the service layer. Im not an expert in this technology by any means but it seems like a potentially dangerous approach, and on top of that it doesnt seem to support any kind of access security as standard (you have to hack it to require authentication it seems).
As I said, this scenario feels like it should have a no-brainer solution, but Im still scratching my head. Ive done lots of things with .NET technologies, but to be honest this area represents a bit of a hole in my understanding, so I apologize if any of my comments or assumptions are naive.
Of course, it may well be that the 'hacky' long-way-round on EF or Linq2SQL may be all I can do, in which case I can roll up my sleeves, and accept the fact that I haven't missed a more elegant solution.
Any help/advice will be much appreciated.
This is a tad subjective, but i'll offer my opinion.
First of all, forget L2SQL - it's basically obsolete and doesn't have the full POCO support of EF4 (it can be done, but needs XML tinkering, or SQLMetal generation), which means serializaing your entities will be a left-to-right entity cloning nightmare.
I would go with ADO.NET Entity Framework over WCF, Entity Framework 4.0 specifically. You will have a wealth of flexibility in your model (including the ability to apply OO principles such as inheritance).
Use Self-Tracking-Entities. Yes, you have to decorate service contracts - this is by design, and there are many reasons for this.
You could always use DTO's, as opposed to serializing the actual EF entities.
OData is really good as well in it's flexibility and simplicity. But if your only consuming your model via a single client application, a specialized service layer (WCF) is a better approach IMO.
3) WCF Data Services - this seems like
a good option on the face of it, but
essentially it seems like I'm just
exposing my SQL database tables 'in
the raw' over the service layer.
That might be a first impression - but it's fundamentally wrong. What you're exposing over the web is a model - and you have full control over what gets into that model, and how consumers of your WCF Data Services might be able to see and/or even update entities in that model.
That's where Entity Framework comes in and shines (and where Linq-to-SQL miserably fails): you can grab your database (or at least parts of it) into an Entity Data Model, and then modify it. You can tweak your entity names to be totally different from your table names, you can add computed attributes, you can remove certain attributes and much more.
If you're talking about a fairly simple app, that's definitely the way I'd go:
grab your database and turn it into an Entity Data Model using EF
expose that EDM over WCF Data Services and define what can be seen read-only, and what might even be updated over the wire
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
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.