Linq to SQL layers/architecture? - linq

I am sorry for my question may looking a old repetitive questions but I as I am starting Linq to SQL I want to discuss how many layers (architecture) should I use ?
I am working on web mostly web sites and small to medium scale web applications. I understand dividing application into layers help its maintainanace and enhancement but frankly I want some balance way which give me rapid development and code reuse-ability as well. I cannot spare so much time on unwanted management of layers.
Before I was using 4 layers (business objects, BLL,DAL and user itnerface.) I became confuse on it as different people have described different layers. Please guide me what and how many layers I should use ? Thanks

Don't use the layer architecture. Use the onion architecture.

The most important aspect from architecture perspective is the separation of concerns. Separation of concerns leads to clean code, easy maintenance, extensible, etc. That said, I recommend to base your decisions based on the following criteria:
Try to architect your system in a loosely coupled way. Use messaging instead of RPC as messaging is reliable, scalable, asychronous, loosely coupled, etc. You can either use MSMQ or NServiceBus (for service bus based architecture).
Create layers based on the separation of concerns concept. For e.g. you can go for typical 3 layered architecture which will have just UI layer, business logic layer (business rules+workflow) and data access layer or more granular such as UI layer, services layer (facade), business logic layer, data access layer, etc. Using IoC / Dependency injection will make life easy as none of the layers will have direct dependency. Moreover, it promotes unit testing easy as you inject mocks instead of the real implementations for the unit test. There are so many IoC frameworks available (NInject, Autofac, Castle Windsor, Structure Map, etc...)
Try to use EF instead of Linq to SQL as the later works only with SQL, while the EF works with any database. Moreover, in my opinion, EF is where microsoft is innovating and I would assume that Linq to SQL may be retired one day.

Great question haansi. This is something that I have wrestled with quite often when building small to medium sized sites. Finding that balance of creating a architecture that gives you the greatest flexibility and allows for rapid deployment is what I think we all need to strive for in all of our work.
With that being said, I have found that using the Repository Pattern to be quite helpful with LINQ to SQL projects. I couple that with the Model View Presenter pattern (for WebForms or other projects) and it provides a great foundation for reuse with minimal layers.
My Webform calls a Presenter class, which in turn is responsible for populating the View. To populate that View the Presenter can call N number of Repositories. The Repository is where you encapsulate your DataContext class and your LINQ to SQL calls. These calls return the model classes.
One huge benefit to this regardless of the size of the app is that get great re-use out of your Repository, you get to maximize the use of LINQ and you have used some patterns that other software developers could easily read and support.
Another big benefit is that you now have created a simple architecture that can benefit from using Unit Testing to test from the Presenter back to the Repository without a ton of effort.
Good luck!

I decided to use one layer (DAL + BLL) for small projects and for large applications will use Different layers for DAL & BLL. I will use Linq in DAL and funtiosn will return IQueryable.

Related

ASP WebApi : Service layer, business layer and data access layer

If I need to write a simple webapi which need to get/create/update/delete of the products. Is this really need a business layer.
I am using Entity Framework which I understand this is similar to Repository Pattern.
If my webapi application is very simple which not much complex business logic e.g. bank reconciliation etc
Do i really need to have a business logic layer? Can i just have a service layer which create products / remove the products etc..
No, it is not necessary at all to have a business layer! (with a disclaimer)
Let me support my argument and address your concern
One of the most basic design principles of software engineering is KISS. If you feel the business problem you are solving is pretty simple then why to make code complex by introducing unnecessary layers.
Not having the 'business layer' is not a crime. It is well supported by the community as well that's why in one of the community and industry loved framework Spring there is a module called spring-data-rest exactly supporting design you are proposing (simple code with business layer and on top without explicit web layer)
The last argument evolutionary approach. With the increasing complexity of system and technology community released that system and code complexity should be evolved (thought process every well explained here). Don't try to think about future today (again referring to another basic design principle YAGNI). (Explaining disclaimer here) So start from simple and if in future you felt the need of having separate business logic layer because you got to write some actual business solving code then introduce that layer and evolve it!

Repository pattern and web api

Hi i learned web api 2 recently and i am working on a sample project now.I am following layered architecture in my project.This is the flow
controller=>Business Layer=>Data Layer
Now i read some article about the repository pattern which sound better nowadays.
i saw the flow like
controller=>services=>repository
Is there any significant difference between the two flows?
As a beginner which style of architecture should i flow?
Can someone help me to understand these patterns?
When you use services with repository you should make it generic and use Unit of Work (UOW) so you don't repeat yourself with CRUD actions on every entity. Then add some object relational mapper (ORM) like Entity Framework. It is prefered that you also use domain objects for storing your logic there, and make the services return data transfer objects (DTO), because best practice is to keep your services small and clean. Then you also need to include some mapping tool/logic to map DTO to Domain objects.
And you see where this is all going. Suddenly you have far more complexity and obstructions than you need. Because only one thing that customer care about is quality of your product not some fancy architecture.
But as project grow it is much more important to have proper architecture, automatic tests etc. , so it is valid in large projects. If you want to experiment and learn it is great opportunity, but if you have running application in production, i would rather not make that big changes.
TLDR: they are both valid

MVC - are there situations when it's either irrelevant or inappropriate?

When developing an app with GUI, and database access, are there situations where the MVC architecture isn't relevant?
To me it seems that the Views and Controllers must only be different entities is one to upgrade the views, or to replace them with something else, namely mobile displays (or predicts such a possible change for the future of the app).
Also, I see the separation of the Model and Controllers only necessary if the Model is to be upgraded / replaced.
So is there any other purpose for the MVC architecture that the situations when components should be upgraded/ changed, or is this really it?
I like MVC because it makes it easier to think about how different parts of the app are going to work together. If everything is just lumped in together, I find it much harder to visualise in my head.
So it's not really a case of when you should use it, rather how do you prefer to think?
If you find it easier not using MVC then you should probably not use MVC.
I think, the root of you confusion is the scope at which you try to apply MVC design pattern.
MVC is not a pattern for small applications. Instead you are supposed to apply it, when your free-form OOP code starts to become unmanageable. Your codebase might be implementing all of the SOLID principles, but at some point you will start getting lost there.
That would be when you should be using MVC, because this design pattern applies additional constraints. It does not add anything new to application. Instead it limits what code can go in what parts of your application.
P.S. you also seem mistaken about what separation there is in MVC. The basic divide is between model layers and presentation layers. Those are two main parts MVC applications. And only then withing the presentation layer there is a separation between views and controllers. You might benefit from reading this article.
For me, it all comes down to testability. Automated testing of UI code is exorbitantly expensive compared to testing of model code. It is much easier to achieve test coverage in model and event controller layers compared to view layers.
If you have no need to test your application, and it is small enough that you can keep it all straight in your head, then MVC is probably a waste of time. Very few applications are truly small enough that these concerns are not at issue. But if the app is truly that small, MVC will add far more overhead than it will provide in value.
Don't think of MVC design pattern as you business architecture. Treat MVC as presentation architecture. There are many arguments about MVC usage in terms of business architecture. This stackoverflow question is one example.
Actually, you are looking for N-Tier architecture. Where it is separated as DAL, BLL and PL:
Data Access Layer (DAL):
A layer responsible to inteact with the Storage (insert/update/delete)
BLL:
A layer where the business logic resides. This layer is the core of your application. Some people often use the term Middleware (please correct me if wrong) to represent the BLL. BLL does not know the UI, means that it can be used by Desktop app, web app, mobile app, etc.
PL:
This is your presentation layer or UI layer. MVC, at least the View and Controller resides here.
There are benefits to the MVC architecture, and there are some disadvantages to it. You have to weigh them for your project to see which would be the most appropriate for you.
Advantages for MVC:
More maintainable because it's compartmentalized (separation of
concerns).
It's more testable because you can unit test the controllers.
You typically have more control over the HTML that gets generated
(Yes, you can accomplish the same with webforms, but only if you give
up all of the advantages of webforms as well).
Your webpages will be smaller and faster because you won't be
carrying around page/view/control state.
Integrates better with client-side lifestyle and libraries
(Bootstrap, jQuery and it's many plug-ins, AJAX, etc)
Advantages of webforms:
More 3rd party controls (webforms relies heavily on either 3rd party controls, or custom usercontrols to achieve rapid application development).
If you need viewstate, then it takes less work, but this is pretty
rare if designed right.
Integrates better with server side control libraries.
Of course, someone is going to say, why did you list xyz as an advantage for whatever, because you can do that in the other one too! Well, you can achieve the same thing in both frameworks, it's just a matter of ease. What is easy for one may be more difficult in the other, but both of them, given enough time and resources can do it too.
MVC is about separation of concerns and making these concerns testable.
Someone said 'MVC is not a pattern for small applications.'. I disagree. Why? It only dictates how you separate concerns, I don't understand why this should be different for small applications. I would argue it's even simpler because every developer uses the same pattern and is used to it. It's not overhead, it's consistency. Also look what this guy has to say.
Another thing: MVC is a presentation layer pattern (Separated Presentation), it means it logically separates your UI in a models, views and controllers. Controllers are responsible for managing the flow, interacting with the backend system to query and save data, and converting that data to models (or view models) that are used by the views.
The backend in itself is another system, which has its own independent architecture, with services, domain and data layer (as for example the onion architecture, of which an example can be found here).

MVC and ORM as designing for asp.net web application

I have a asp.net project and Its in designing phase. Its about products and shops navigation system. Users can browse/search products. I want my web application to be extendable and flexible. What I initially planned was to make it an MVC and for database I propose ORM (Object Relational Mapping). Is that right? what could be the problems I face with this proposal. I am learning asp.net so I don't know much about the problems.What design do you people suggest?
It's great that you've decided to learn ASP.NET.
Regarding design approach, it sounds like your question is 2 part: a) MVC or traditional web forms ASP.NET, and b) ORM or no ORM.
a) Generally speaking, if you have a good programming background, I would recommend MVC over web forms for any consumer facing Internet product. It promotes testability, clear separation of concerns, and gives the developer finer grained control over the UI.
b) Regarding ORM or no ORM - first, its important to note that you still need to choose a database. ORM is merely a means of abstracting the data access logic away from the developer - but there still needs to be a database to store the data. If you're going with an all Microsoft stack, you'll probably choose SQL Server.
ORM is great for developer productivity - and generally speaking, there's no reason not to choose it for new projects unless you can identify up front that its not going to provide a productivity boost. An example reason why you would choose not to adopt ORM - you need to persist the data in a pre-defined format - or in an already existing database - and the persisted entities are not consistent with how your application is representing them (i.e. over-normalized). In this case, you may want to write your own data access logic, and not rely on an ORM.
Finally, if all you are looking to accomplish is putting a product catalog online, rather than building an application from scratch to do this - you may want to consider utilizing an existing CMS of some sort, or even use Wordpress with some plugins. Would save hours of time and still accomplish your stated goal.
Best of luck!
If you want a really good reference on how to build application using MVC and ORM, then read the following book : Professional ASP.NET Design Patterns
It explains in details as how to build application using MVC. It also covers other interesting topics like dependency injection, repository pattern(very important expecially if you have decided to go for ORM), TDD etc. I hope you will enjoy reading this text.

web development - MVC and it's limitations

MVC sets up clear distinction between Model, View and Controller.
For the model, now adays, web frameworks provides ability to map the model directly to database entities (ORM), which, IMHO, end up causing performance issues at runtime due to direct database I/O.
The thing is, if that's really the case, why model ORM is so pupular and every web frameworks want to support it either organically or not.
To a web site has huge amount of traffic, it definitely won't work. But what's the work around? Connect directly to database is definitely not a wise solution here.
What's your question?
Is it a good idea to use direct db access from webpages?
A: No.
Is it a good idea to use ORM's?
A: Debatable : See How can I design a Java web application without an ORM and without embedded SQL
Is it a good idea to use MVC model?
A: Yes - it has nothing to do with "Direct" database access - it's about separating your application logic from your model and your display. (Put simply).
And the rationale for not putting database logic inside webpages has nothing to do with performance - it's about security/maintainability etc etc. Calling a usp from a webpage is likely to be MORE performant than using an ORM, but it's bad because the performance gain is negligible, and the cons are significant.
As to workaround: if you mean how do you hook up a database to a web application...?
The simplest way is to use something like Entity Frameworks or Linq-Sql with your Model - there are plenty of examples of this in tutorials on the web.
A better method IMO, is to have a separate Services layer (which may be WCF based), and have all the database access inside that, with DTO's transferring the data to your Web Application which has it's own ViewModel.
Mvc is not about orm but about separation of display logics and business logics. There is no reason your exposed model needs to be identical to you database model and many reasons to ensure that the exposed model closely matches what is to be displayed.
The other part of the solution to scale well would be to implement caching in the control and be able to distribute load on sevaral instances.
I think #BonyT has given a good answer, (and I've voted for it :) ), I'd just add that:
"web frameworks provide the ability to map the model directly to database entities (ORM), which, IMHO, ends up causing performance issues at runtime due to direct database I/O"
Even if this is true, using an ORM can solve a lot of problems with a model being easy to update and translate back and forth between a database. Solving a performance hit by buying extra web servers or cloud instances is much cheaper than having to buy extra developers or extra hours in development to solve things other people have already written ORMs to do for you.

Resources