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

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

Related

MVVM and ORM tools

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.

WPF App with WCF Data - EF, Linq2Sql or WCF Data Services - None Seem 'Easy'

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

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.

Marrying up consumer-defined aggregates (e.g. SQL counts) with 'pure' model objects?

What is the best practice of introducing custom (typically volatile) data into entity model classes? This may sound like a bad practice first, but it seems to be quite a common scenario. In our recent web application we have developed a proper model and in most cases we are fine with loading model entities. But there are cases where we cannot afford loading an entire hierarchy of entities; we need to load, say, results of a couple of SQL COUNT’s or possibly some additional information alongside (or embedded inside) the model entities. So basically, the requirements and conditions are:
It’s a web application where 99.9999999999% of all operations are read operations.
They don’t need to process or do any complicated business logic. We just need to get data quickly to HTML.
In several performance critical cases, we need to load results of SQL aggregates which don’t fit any model properties.
We need an extensible way to introduce any new custom data if needed.
How do you usually solve this issue without working too much around your ORM (for instance raw data from db)? I’m sure this has been discussed many times, but I cannot figure out a good Google query to find anything useful.
Edit: Since I later realized the question was not very well formed, I decided to reformulate it and start a new one.
If you're just getting relational data to and from a browser, with little or no behavior in between, it sounds like your trying to solve a relational problem with an OO paradigm.
I might be inclined to dispense with the Object Oriented approach altogether.
Me team recently rewrote an application by asking "What is the simplest thing that can possibly work?" and "What is the closest language to the problem?". Our new app, replacing an OO one, ended up being 10 times smaller, faster, and cheaper.
We used SQL, stored procedures, XML libraries on the DB server, XSLT (to get the HTML), and javascript.
OOP purist like myself would go to the Decorator pattern.
http://en.wikipedia.org/wiki/Decorator_pattern
But the thing is, some people may not need the flexibility it offers. Plus, creating new classes for each distinct operation may seem overkill, but it provide good compile type checking.
The best practice in my view is that your application consumes data using the Domain Model pattern. The Domain Model can offer business-logic methods for doing the type of queries that make sense and are relevant to your application needs.
These can fetch "live" results that map directly to database rows and can therefore be edited and "saved."
But additionally, the Domain Model can provide methods that fetch read-only results that are too complex to be easily saved back to the database. This includes your example of grouped aggregate query results, and also includes joined query result sets, expressions as columns, etc.
The Domain Model pattern offers a way to decouple the OO design of an application from the design of the physical database.

Is ActiveRecord bad practice?

I'm starting a new project and i've recently found castle project activerecord, which seems like a GREAT solution, but at the same time, it looks like something realy unconventional.
I was wondering, does this feeling comes from learning something new (and i should just get used to it) or is really bad practice?
Part of what felt weird to me about using ActiveRecord was having to inherit from ActiveRecordBase<T>, and having all those persistence methods on your object (Save and so forth).
But it turns out you don't have to! Instead of having, say:
[ActiveRecord]
class Customer : ActiveRecordBase<Customer> { }
You can just have
[ActiveRecord]
class Customer : inherit from whatever you want { }
and then use ActiveRecordMediator<Customer>. It has basically the same static methods that ActiveRecordBase<T> has, but this way you don't have to clutter your object model with them. If you don't need the various protected method event hooks in ActiveRecordBase<T>, this can make things simpler.
ActiveRecord is a design pattern first named by Martin Fowler in Patterns of Enterprise Application Architectures. It is fairly common and used extensively in the popular Ruby framework Rails.
It contrasts with the more usual style of development in the .Net world which is to use DAOs, and that perhaps explains why you're uneasy.
A suggestion: read the source code for some Ruby on Rails applications which are similar to your own projects, and evaluate how you like the design style that results from heavy use of ActiveRecord.
It's not a bad solution but it has it's downsides.
In Patterns of Enterprise Application Architecture Martin Fowler describes several ways of designing applications that are built on top of a database. These methods differ in the way the application is decoupled from the database. He also describes that more decoupling makes more complex applications possible. Active Record is described as a way to design simpler applications but for applications with more complex behaviour you need a Domain Model that is independent of the database and something like an object-relational mapper in between.
ActiveRecord works very well in Ruby, but it's not easily transferable to all languages. The central feat of AR is the metaphor of table=class, row=instance. This comes out quite elegant in Ruby, because classes are also objects. In other languages, classes are usually a special kind of construct, and then you have to go through all sorts of hoops to make it work like properly. This takes away some of the natural feel that it has in Ruby.
The mixture of the domain object with the service layer is the biggest bad practice (if you see that as a bad practice). You end up calling user.Save() which means if you want to change your ORM, you are reliant on this pattern. The 2 alternatives are a layer aka a set of facade classes to perform your CRUD operations, or to put this inside the domain object as something like
User.Service.Save(user);
If you're using .NET then ActiveRecord is obviously ActiveRecord based, Coolstorage, Subsonic and a few others.
No it's not bad practice. Even in .NET it's a fairly well established pattern now. SubSonic (http://subsonicproject.com) and LINQ to SQL also use the pattern.
Implementations of the pattern, such as Subsonic, are great for quickly and easily creating a data access layer that manages the CRUD for your application.
That doesn't mean it's a good solution for all systems. For large, complex systems you probably want to have less coupling to the data store.
I think ActiveRecord has not much to do with Castle and therefore, the answers to this question Does the ActiveRecord pattern follow/encourage the SOLID design principles? could be more enlightening to many.

Resources