Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have started using an onion architecture because I wasn't satisfied with my previous project structure. My main question is, can I return DTOs from the data access layer?
This is my current structure:
/Core
- Application
- Domain
/Infrastructure
- Persistence
- Identity
/WebApi
- WebApi
Quick explanation:
Application layer is where I have all my business logic
Domain layer is where all the entities/models are defined
Persistence layer is where I query the database
Identity layer is for user management
WebApi layer is where I have my controllers
The data flow is the following:
Client <- WebApi Layer <- (DTO) Application Layer <- (Entity) Persistence Layer
As of right now, the persistence layer returns the actual database entities which are defined in the domain layer which the application layer transforms to DTOs.
My problem here is that often, the persistence layer actually needs to perform different queries which will make the type different from the entity type. For example, I could join different tables, apply groupings, etc. Thus, I cannot return an entity type.
Am I allowed to return DTOs from the persistence layer (data access layer)? If yes, where do I defined these DTOs? Defining them along with the other DTOs in the application layer and using these DTOs in the persistence layer would make it dependend on the application layer (not so great in my opinion since we want to minimize couplings). Another option would be to create them in the domain layer along with the entities (probably the better approach)? For consitency's sake, should I only return DTOs from the application layer or is it fine to return entity types as well as DTOs?
Lots of questions that I couldn't find. Just trying to become a better programmer:)
My main question is, can I return DTOs from the data access layer?
Yes. Noting that:
Yes, because who's going to stop you?
Yes, as in it's a common enough recognized pattern, and generally speaking no kittens will die if you take that approach.
Am I allowed to return DTOs from the persistence layer (data access layer)? If yes, where do I defined these DTOs?
My default "in the absence of a reason not to" architecture for layered apps is to use DTO's, which I typically define in a common library. Detailed write-up of that here (pdf). The Data access, business logic and UI all share this as a common vocabulary.
This makes them useful for where you use Dependency Injection to abstract out your data access - the interfaces you define will also have to use the DTOs in their signatures.
If you want to, you could define DTO's that only the data access layer, and it's consumers know about - the question is why would you want to? Not to say you can't - only that you should only do that if you have thought it through and have a meaningful reason to do it.
My problem here is that often, the persistence layer actually needs to perform different queries which will make the type different from the entity type. For example, I could join different tables, apply groupings, etc. Thus, I cannot return an entity type.
Sometimes you'll have scenarios where the DTO's you create are very scenario specific (don't get reused). Only you can say if that's acceptable or not. It's a trade-off between how much code you want to maintain, and how fit-for-purpose DTO's are. I don't think having scenario specific DTO's is bad in of itself, if it means the architecture remains clean and how you implement the scenario is sensible.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Ok, so I have been trying to wrap by head around domain driven development (DDD).
I know that POCO classes are supposed to be simple and that they have no connection with entity framework. These are the classes will be mapped to entities when any database operation is needed.
I also know that in DDD, you have your classes with all of your business logic in it.
My question is, if I start putting logic and method inside my POCO classes, they will not stay simple anymore, but If I start creating and using my domain classes separately, I ll need to first map my domain object to POCO and then that POCO object to entity object and vice versa, which is getting hectic.
So should i go like: Entities <--> POCO (Simple class) <--> Domain Object (All business logic) or should I get rid of POCO classes and instead use domain classes only, since I am getting the work done including layer separation between BL and EF entities anyway.
Thank you.
By definition, POCOs do not have any logic within them. They're mainly a holder class, consisting only of various fields and properties. Once you start adding logic into them, you start heading further down the road of domain driven design.
Many developers, like Martin Fowler rightfully argue that widespread use of POCOs lead to an Anemic Domain Model, which Wikipedia defines as: "...the use of a software domain model where the domain objects contain little or no business logic". In my opinion, an anemic model while using EF is definitely a real risk if you do not take proactive measures to mitigate it.
That's not to say every system employing POCOs for entities is inherently doomed to produce an ADM. In fact, Jason Taylor has an amazing talk on Clean Architecture, and his Northwind Traders demo shows some great ways to potentially segment your application without sacrificing much clarity.
Modern Entity Framework Core lends itself very well to both design paradigms (POCOs and DDD), so there really is no "right" answer. I personally take a hybrid approach in most of my nontrivial use-cases. My entity models contain the hard and fast, universal domain rules for the entity; not to be confused with the domain logic. My domain layer contains most of the pertinent domain logic, or rather how various entities interact with each other. My application layer brings everything together, and it encompasses the actual logic responsible for making the program operate.
I do still have POCOs, but they're primarily used to transmit data to and from the client. I use them in conjunction with AutoMapper and FluentValidation to simplify the boilerplate code, but they're by no means necessary.
So when it comes to the POCO question, the answer is: "It depends".
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have read lots of articles and they seem to vary from one author/developer to the next. In my situation, I am thinking about this setup for testing a project:
Presentation Layer via ASP.NET MVC
Service Layer (my plan is ASP.NET MVC Web API; this is on separate assembly)
Business Logic Layer
DAL using EF
Some articles said I should not put CRUD operations on BLL and BLL should only contain business logic. Also, some said BLL should not access DAL. But what if a business logic needs data stored in DB to calculate/work on logic? I guess my questions would be:
If BLL shouldn't access DAL, how about those business logic that needs data in DB for it to be able to perform the logic?
BLL are entities, right? Are they the same as POCO or would I still have POCO in DAL?
Also, is DBContext in BLL? Some say it should so I'm confused.
What about the no CRUD in BLL? Should I do that?
Repository interface is in DAL?
Any additional comments/suggestions/information on what my planned setup would be very welcome (even if it is not related to BLL).
I worked on a project some time ago.
Our project arquitecture ressembled to what you suggest.
We had an ASP.NET MVC site, which accessed a WEB API (in an external solution).
The WEB API also referenced an external solution entirely made up of static libraries, which contained the data layer (just entities) and the persistence layer.
We also had Data Transfer Objects (MSDN) for communication between the web service and the clients, and to decouple the entities entirely from external solutions.
We had the business logic in the WEB API project. We would create, manipulate and store the entities from within the WEB API HTTP methods.
But we didn't accessed the data and persistence layer directly, we had an intermediate layer, we called it entities manager. These managers would be injected on our WEB API controllers (We used Ninject for Dependency Injection) and would handle the creation of the entity, and also the persistence, so we'd decouple everything.
This approach worked very well for us, and we made a pretty well maintainable and scalable project.
I hope it may be of help for you, and of course, there probably exist better techniques.
PS:
We used an IRepository interface provided to us by the entites manager to persist the entities. This was our only access to the persistence layer. Inner logic, such as persistence strategies (like EF's DbContext, or File IO) would be internal to the persistence project.
This is an example of our bussiness logic in one of our WEB API HTTP methods:
// "repository" is an IRepository<Entity>
entityManager.Transaction( (repository) => {
Entity ourEntity = repository.CreateNew();
//Manipulate the entity somehow
repository.Add(ourEntity);
});
The data will take different forms, for example in the data storage DS (SQL Server for example) they are on relational tables, in the data access layer DAL they are in the Data Model (object model) like Entity Framework EF, in the presentation layer PL they would be in View Model, and on the HTML page or desktop form they will live inside a UI component.
At a single point when a layer calls another layer they have to have a communication channel and a data container that would change the data from one form to another.
Whenever a DAL asks for some data from DS it should be changed from table form to a object model form, so the DAL does not care about the table form. When you send the data back from the DAL to the PL it should be changed to be in a View Model form and again the PL does not care about the object model form, and so on.
You might ask about the BLL layer, I guess this layer most of the time is just a delegate in the middle when there is no logic in the middle, so for some performance matters the PL would access the DAL directly.
I hope this would answer your questions.
EDIT
For the BLL you consider as the mind of the system, the PL is just showing what it receives, and DAL just returned what is asked for to return by acquiring the right DS entities. So the CRUD would be in the DAL.
For Example you need to search for a list of employees, the BLL here is just a delegate layer where it delegates the PL call to the DAL and return back the results. But in case of adding a new employee, the BLL would have an interface with function like AddNewEmoloyee which will do some business logic functions like for example making sure that the salary is according to the employee level range, and then it will call the needed CRUD actions in the DAL.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Let's say i have a blog with posts by different authors, and the authors should be able see what articles they have written.
Now i write a query using db context of entity framework.
Now the question is where should the query go in the specific action method of the controller or the model class.
I am kinda new and this thing has been confusing me.
Controllers should be as lean as possible
So the best place to put the query is outside the controller action, typically place for the all kind of the persistence queries are repositories (Repository Pattern) or some business logic layer - really depends of the complexity of the application.
In short Repository Pattern is really about that there is only one place in the application that contains the knowledge of the persistence and how to query it, typically we can find CRUD operations in there. Also typically you have one repository per "domain context" (Order, Blog post, ...).
For example (the workflow for a small app):
OrderController -> OrderRepository -> Persistance
CreateOrderAction -> SaveOrder -> Query
Because. Think about it. What if you have OrderController and then let's say a SpecialOrderController but both needs the Order data? In that case you end up with query code duplication, if a case of the repository pattern you avoid this "trap". As you know DRY principle is one of the greatest in our craftsmanship.
It depends on the layers of your application. The fact that it's MVC doesn't matter. Do you have a data layer? If so, it goes there.
This is a little bit like asking where your queries would go in a WinForms app. Again, if this is a non-trivial app, you probably have a UI, maybe a service layer, a business logic layer, and a data layer. The data layer is where your queries go.
In an MVC app, the controller knows how to react to events in the view. In apps that I've worked on, the controller will make a call to the business logic layer, and the BLL will then connect to the data layer. This would be overkill in trivial apps, but I'm not sure how extensive your application is.
The BLL and DAL are your model. So, the short answer is:
The queries belong in the model, not the controller.
I would put those kinds of queries into a repository class; that way you are enabling the use of the same queries in multiple parts of your application.
I Am creating a web application and first use Entity Framework. I created Entity Data Model and now I am not sure, how to proceed now.
Premise: My database is really simple (Rating, WebPage, Visitor) and database tables corresponds to the business objects.
My suggestion is 3tier architecture but how to make it?
It is good idea create partial classes with the same name as Entity Framework objects (Rating, Visitor) and declare here new methods (GetAverageRating()...)? Or is better create some VisitorProvider, RatingProvider and place logic here?
It is better use EF objects in BLL and Presentation Layer or I should create my own BO objects on my BLL layer and transform EF object to BO?
I'm think, it is more practical use static methods on my DAL than instantiate classes on BLL. Do you agree?
Can you recommend me some best practices? I have many ideas how to create it, but I do not know what is the right.
3 layer architecture is quite popular but what it really means?
Presentation layer
Application layer
Database layer
If you ask what each layer means you can be pretty sure you will get several different answers. You can further divide each layer into sublayer and build layered hell like:
Client side presentation layer
Server side view layer
Controller layer
Service facade layer
Service layer
Domain objects layer
Repository + Factory layer
ORM layer
Stored procedure layer
Database view layer
Database table layer
WTF? That is just example that application can be easily over architected. It can go even worse if you insist that only neighbours can exchange data and if you decide to add special type of objects to be exchanged between layers instead of flowing sing set of objects through multiple layers.
Add layers which you need to make you more comfortable with developing the application and which will do reasonable separation of concerns and maintainability needed for the scale of your application. You can simply do the most simplest application which will be used just few weeks and must be developed as fast as possible. In such case you can do that within few days simply by using ASP.NET web forms and data source controls (or ASP.NET dynamic data). It can be badly extensible but in such situation it is exactly what you need to implement application quickly. Writing layers and doing all the stuff around maintainability and extensibility is reasonable if you need it. Another quick prototyping technique is ASP.NET MVC Scaffolding which can create quick multilayered skeleton of the application which can be further modified.
Both approaches are correct and it only depends on the approach you like. The first is called active record pattern but it is not used very often with entity framework. The second approach is more popular. You can either use EF directly in some middle class which you called Provider (common name is also Service). This class will do both data access logic and business logic. In more complex applications developers like to somehow wrap EF to separate class following repository pattern and call the repository either from service or directly from web app. code behind or controller (depending on amount of business logic). Try to do it without repository first. My personal opinion is that people should start to use repository only once they understand EF itself.
Again both approaches are correct. In a simple application it is fully acceptable to create EF model with POCO classes (EFv4.x) and use them in all layers. If you are using ASP.NET MVC you can find that you need special classes as view models to fully represent needs of your individual views. In a more complex application you can have separate objects exposed from a business layer - this is especially used if the business layer is exposed as a remote service (WCF).
It depends how you write these DAL methods - it is absolutely necessary to not share the EF context among requests! It also depends if you want to write some test or not. Layer defined by static methods is something which goes directly against testable architecture where you want unit test just single layer (unit testing with EF can be hard). It also depends if you want to use dependency injection which is based on instances.
is itIa good coding standard to allow ASP.NET MVC controller actions to access a repository directly (even though a service layer is present for the heavy lifting, e.g. LoginService.Authorize() ) to retrieve, add, or update data? Or should everything go through the service, and from there to the repository?
For smaller applications/webs, i tend not to use service layer, because it just maps Repositories methods 1:1, and I loose KISS. But in the end, it depends on business model; repository abstracts db access, and services encapsulates logic.
It's better to go through the service layer (depending on how you've implemented it though), because that's the point of it - to be a single access point, thus any business-specific things you do there, are represented and implemented across all callers.
It really depends on the complexity. If you're dealing with any transcation scoping, I'd definitely decouple that away from the controller into your service layer.
In my opinion it will depends on your design/architecture. What's the purpose of a repository ? Do CRUD operations (Create, Read, Update and Delete).
If you're using the anemic domain models in a classic three-tiers architecture all logic applied to the models are made in the services.
In this case the choice is obvious : You shouldn't call the repository directly.
Why ? Since your models are silly and the logic is in the services you could create invalid models. If you can call the repository you could create/update an invalid model in database. If you call the services it should be able to correct or fill your model before create/update it.
If you're using a rich domain model in an onion architecture it's different. Since your models are supposed to be always valid (when you create one from the constructor or from the factory all validations has been performed and when you update one it's the same thing) you can without any problem call directly the repository.
In this context all the logic is in the models directly and the services are just used to stored the logic that doesn't belong to one model specificly.
Now the question is not "how to use repository" but "what design/architecture do I need ?" and the first question will be answered :-)