Dto/TransactionScripts and Odata Services - odata

With an odata service, we can query from the clientside without using dto. Do i really need dto layer if i use odata svc? What are the cons and pros if i don't use dto. In our old system for querying mechanism there are many query service-methods that returns dto collection. But odata services confuses my mind... It seems like; the responsibility of server moves to the client. The same confusion goes on, for transaction scripts. I'm curios about your thoughts.

When you are on the server side - the only thing that matters for oData is either a EDM model or POCO models. So when you genrate a EDMX file you can always considered those to be your business object or model layer and pump then in to those namespaces. So in a way there is no business logic that you are applying in there.
But on the client side you can always centralize the oData method invocation. Since they support callbacks you can always have a view model call up a repository and pass the call back. In this way you dont bloat your view model with extensive odata query invocation. Sort of repositroy pattern is what i am talking about.
Hope this gives you a direction.
regards :)

Related

Service layer and project structure in ASP.NET MVC 5 without repository and UoW patterns

I'd like to create a good app in ASP.NET MVC 5 using EF 6 Code first concept. I want it to be well-designed i.e. having generally speaking: Presentation, Logic and Data layers separated. I want it to be testable :)
Here's my idea and some issues related with creating application
Presentation layer: It's my whole MVC - view models(not models), views, controllers
I believe that's validation should be done somewhere else (in my opinion - it's a part of business logic) but it's quite convenient to use attributes from the DataAnnotations namespace in ViewModelds and check validation in controller.
Logic layer: Services - classes with their interfaces to rule business logic.
I put there functions like: AddNewPerson(PersonViewModel Person), SendMessageToPerson(...).
They will use DB context to make their actions (there's a chance that not all of them will be relying on context). There's a direct connection between service and db - I mean the service class have reference do context.
Where should I do mapping between ViewModel and Model? I've heard that service is a bad place for it - so maybe in controllers. I've heard that service should do the work related with db exclusively.
Is it right? Is my picture of service layer is good?
Data layer: I've read about Repository and UoW patterns a lot. There're some articles which suggest that EF6 implements these two things. I don't want to create extra code if there's no need for such a behavior. The question is: am i right to assume that i don't need them?
Here's my flow:
View<->Controllers(using ViewModels)<->Services(using Models)<->DB.
**I'm gonna use DI in my project.
What do you think about my project structure?
There is no reason to use a Unit of Work pattern with Entity Framework if you have no need to create a generic data access mechanism. You would only do this if you were:
using a data access technology that did not natively support a Unit of work pattern (EF does)
Wanted to be able to swap out data providers sometime in the future.. however, this is not as easy as it might seem as it's very hard NOT to introduce dependencies on specific data technologies even when using an Unit of Work (maybe even BECAUSE you are)... or
You need to have a way of unifying disparate data sources into an atomic transaction.
If none of those are the case, you most likely don't need a custom Unit of Work. A Repository, on the other hand can be useful... but with EF6 many of the benefits of a Repository are also available since EF6 provides mocking interfaces for testing. Regardless, stay away from a generic repository unless it's simply an implementation detail of your concrete repositories. Exposing generic repositories to your other layers is a huge abstraction leak...
I always use a Repository/Service/Façade pattern though to create a separation between my data and business (and UI and business for that matter) layers. It provides a convenient way to mock without having to mock your data access itself and it decouples your logic from the specific that are introduced by the Linq layer used by EF (Linq is relatively generic, but there are things that are specific to EF), a façade/repository/server interface decouples that).
In general, you're on the right path... However, let me point out that using Data Attributes on your view models is a good thing. This centralizes your validation on your model, rather than making you put validation logic all over the place.
You're correct that you need validation in your business logic as well, but your mistake is the assumption that you should only have it on the business logic. You need validation at all layers of your application.. And in particular, your UI validation may have different requirements than your business logic validation.
For instance, you may implement creating a new account as a multi-step wizard in your UI, this would require different validation than your business layer because each step has only a subset of the validation of the total object. Or you might require that your mobile interface has different validation requirements from your web site (one might use a captcha, while the other might use a touch based human validation for instance).
Either way, it's important to keep in mind that validation is important both at the client, server, and various layers...
Ok, let’s clarify a few things...
The notion of ViewModel (or the actual wording of ViewModel) is something introduced by Microsoft Martin Fowler. In fact, a ViewModel is nothing more than a simple class.
In reality, your Views are strongly typed to classes. Period. To avoid confusion, the wording ViewModel came up to help people understand that
“this class, will be used by your View”
hence why we call them ViewModel.
In addition, although many books, articles and examples use the word ViewModel, let's not forget that it's nothing more than just a Model.
In fact, did you ever noticed why there is a Models folder inside an MVC application and not a ViewModels folder?
Also, ever noticed how at the top of a View you have #model directive and not # viewmodel directive?
That's because everything could be a model.
By the way, for clarity, you are more than welcomed to delete (or rename) the Models folder and create a new one called ViewModels if that helps.
Regardless of what you do, you’ll ultimately call #model and not #viewmodel at the top of your pages.
Another similar example would be DTO classes. DTO classes are nothing more than regular classes but they are suffixed with DTO to help people (programmers) differentiate between all the other classes (including View Models).
In a recent project I’ve worked on, that notion wasn’t fully grasped by the team so instead of having their Views strongly typed to Models, they would have their Views strongly typed to DTO classes. In theory and in practice everything was working but they soon found out that they had properties such as IsVisible inside their DTO’s when in fact; these kind of properties should belongs to your ViewModel classes since they are used for UI logic.
So far, I haven’t answered your question but I do have a similar post regarding a quick architecture. You can read the post here
Another thing I’d like to point out is that if and only if your Service Layer plans on servicing other things such as a Winform application, Mobile web site, etc...then your Service Layer should not be receiving ViewModels.
Your Service Layer should not have the notion of what is a ViewModel. It should only accept, receive, send, etc... POCO classes.
This means that from your Controller, inside your ActionResult, once the ModelState is Valid, you need to transform your ViewModel into a POCO which in turn, will be sent to the method inside your Service Layer.
In other words, I’d use/install the Automapper nugget package and create some extension methods that would convert a ViewModel into a POCO and vice-versa (POCO into a ViewModel).
This way, your AddNewPerson() method would receive a Person object for its parameter instead of receiving a PersonViewModel parameter.
Remember, this is only valid if and only if your Service Layer plans on servicing other things...
If that's not the case, then feel free to have your Service Layer receive, send, add, etc...ViewModels instead of POCOs. This is up to you and your team.
Remember, there are many ways to skin a cat.
Hope this helps.

When is it good to use both DTOs and Breeze?

I've built my WebAPI to serve DTOs to the client as a means of separating the domain models from the client-side models. I'm now ramping on client-side technologies like Breeze and I'm wondering how using Breeze would affect this pattern, and if it's an either/or kind of scenario. When is it a good idea to use both breeze and DTOs, if ever?
Breeze doesn't really care whether you want to use a DTO or a more full fledged domain model 'Entity' object. From a .NET perspective, Breeze can apply its full range of query services to any collection that can be exposed as an IEnumerable or an IQueryable. If you don't want to use queries, you can expose individual DTO's or collections of DTO's via WebApi methods that take parameters.
You also have the option of using Breeze queries with projections to construct DTO objects from entities on the server and only work with the DTO's on the client.
If querying is important to you, then the primary issue with DTO's vs domain model 'Entities' from your perspective is how easy it is for you to expose your DTO's as 'Queryable' objects and how efficient this querying is likely to be. Many ORM tools, like Entity Framework, are able to transform a query so that most of the heavy processing is performed by the Database engine. Such optimizations can be very performant in comparison to the alternative of trying to iterate over a DTO collection in order to execute a query.
One interesting alternative is to use something like the Entity Framework and WebApi to expose only the mapped subset of your domain model that you want exposed on the client. i.e. you use the Entity Framework to do your DTO mapping for you. So you have two EF models, a full domain model and a DTO domain model. The advantage of this, is that you still get the advantage of query optimization.
Hope this helps.

Using breeze js not to interact directly with DBContext

I'm very new with breezejs and having a few questions.
I think that breezejs has very nice features so I can replace my own datacontext. However, I don't want breezejs to interact directly with the dbcontext layer. In fact, in my application, the Service layer only exposes ViewModels - not even the real Business models - to the Controllers . So i'm not so sure whether I can use Breeze or not, since in few Breeze's examples, I only saw Breeze interact directly with DBContext.
Thanks.
=========================================
Thanks Ward for the answer,
About the features that I like from Breeze is that it will help to reduce a lot of time to build my own client-side view models. And to build a SPA, maintaining client-side view models is really painful for me, especially my application have desktop app client and other hand-held device's apps as well. Also, to handle the mapping from a JSon object to Knockout - which means with each view models, I will need a mapper as well.
Currently, my architecture is like this:
Server-side:
Repository layer <=> Service layer <=> Controllers (with the Web API that exposes to Client-side)
Controllers only can get the data (in format of a View Model) by sending request through Service.
So, my question is whether it is possible to make use of Breeze to query and also its integration with knockout.
Breeze never works directly with your DbContext; it works with the service model that you expose through endpoints on your service (e.g., Web API controller methods). But you certainly get the most value from Breeze when the client can query and save entities that are structurally the same as entities on the server.
You can retrieve ViewModels with Breeze - you can call almost any HTTP service method with Breeze. It's not clear to me how Breeze would help you manage those ViewModels on the client once you had retrieved them.
What features of Breeze seem "very nice" to you? Your answer to that question will help you determine if Breeze can be helpful with your preferred architectural style.
Querying data through Breeze without API controllers using DBContext directly should be no problem, saving might be harder but still manageable. I think the most complicated part is to get metadata to the client.
According to this SO answer, samples for exposing metadata from other sources that DBContext directly should be out in a week or so.
Meanwhile, check BreezeJS spa-template sample as there is repository pattern involved on the server side which makes it similar to your data access setup.

Domain Entities, DTO, and View Models

I have an ASP.NET MVC 2 application with a POCO domain model and an NHibernate repository layer. My domain model has no awareness of my viewmodels so I use automapper to go from viewmodel to entity and vice/versa.
When I introduced WCF to my project (a late requirement), I started having to deal with disconnected objects. That is, I retrieve an entity from the database with NHibernate and once that entity is serialized it becomes disconnected and each child collection is loaded regardless of whether or not I plan on using it meaning I'm doing alot of unnecessary database work.
After reading up on this, I see that it is highly recommended that you not expose your entities outside of your domain project and you should instead use DTOs.
I see the reason for this but I'm having trouble figuring out how to implement it.
Do I map from viewmodel to DTO in ASP.NET MVC, send DTOs through the service layer, and map from DTO to entity in the service layer? Where should I define my DTOs?
I like to have my service layer keep entities encapsulated within it, and return/receive only DTOs. I keep the service contracts as well as the DTO's in a separate assembly which both the MVC project and the Service implementation reference.
Inside the service call implementation, the service maps dto's to entities, then does the interaction with repositories and other entities as it needs to.
On the app/mvc project I sometimes will get lazy and just use DTO's as the models for certain actions (especially CRUDy ones). If i need a projection or something like that, then I'll make a viewmodel and convert between DTO and viewmodel with automapper etc.
How exposed your entities are is a subject of much debate. Some people will push them all the way to the view/app layer. I prefer to keep them in the service layer. I find that when the entities leave the service layer, you find yourself doing business logic type stuff anywhere where they're interacted with, stuff that should probably reside in a service.
I treat my DTOs like ViewModels because the UI layer ( MVC app ) is requesting them. You could go Entity -> DTO -> ViewModel but I think thats over engineering if the only consumer of your service is an MVC application. If somehow the DTOs will actually be used for data and not simply screen specifications then you should probably use additional mapping.
I've also simply returned entities from my WCF layer and let the automatically generated proxy objects on the client be the DTO. The entities almost become DTOs because of the proxy classes and no business logic comes over to the client.
And of course, this is all "It Depends" what your architectural goals are. This question is borderline subjective and argumentative IMHO.
I like defining the DTO in the MVC project and then creating extension methods to transform from domain entity to DTO (and vice-versa).
The transformation would take place in the mvc functions.
I just wrote a post about a way of getting around all this DTO <-> DO transformation. Maybe you check it out http://codeblock.engio.net/?p=17

Repository Pattern - MVC storefront

Have been looking at the MVC storefront and see that IQueryable is returned from the repository classes. Wondering if you are not using LINQ does it makes sense to return that object? In the case of LINQ in makes sense because of deferred execution, so adding filtering in the service layer makes sense, but if you don't use LINQ you would want to filter in the DB in many cases. In this case would I just add methods that do the filtering to the repository? If I do, is the service layer really useful?
Arguments can be made either way, see this recent blog posting: Should my repository expose IQueryable?
The IQueryable stuff that Rob Conery put into the MVC Storefront is innovative, but by no means the norm when it comes to creating repositories. Usually, a repository is responsible for mapping your domain to and from the database. Returning IQueryable doesn't really perform any mapping and relies on the services layer to do that. This has its advantages and disadvantages, but suffice it to say that it's not the only way to do it.
You will notice, however, that your services end up becoming a little smelly because of all the duplicate code. For instance, if you just want to get a list of all the users in your database you'd have to define that function in both the repository and the service layer. Where the service layer shines, however, is when multiple transactions to/from the database are needed for one operation.
The issue I have with exposing IQueryable to the Service Layer is that if you ever wanted to wrap the Repository layer behind a Web Service without breaking the Service Layer code you couldn't, well not without using ADO.NET Data Services but then all your Repository code would essentially become redundant.
Whilst I think it can be pretty productive for small apps, when you start looking at scaling and distribution it does more bad than good.

Resources