Dont we need DAL Layer In MVC3 architecture? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where to write Database and Business logic in MVC?
I have just started with MVC3 pattern. How do we do data access in MVC3? Do we make the 'MODEL' as Data Access Layer or Do we add another 'DAL' layer and call it from 'MODEL' Layer?

Your model should be independent of data-access stuff, which will allow you to change your DAL strategy in the future.
You should be feeding the model from the DAL, but the model shouldn't know how it is being constructed, and certainly shouldn't have any database-specific code in it.
If you take the approach I suggest, look at AutoMapper - a very useful tool for mapping data between DAL and model classes.

When I was working with my last MVC3 project, my understanding from the various samples (such as GeekDinner) was that the Entity Framework serves as the Data Access Layer.

Your Model can be a directly mapped data access object, but don't necessarily have to be. They could just as well be proxies through to your backend DAL which is always going to be the better option depending on your requirements and longevity of the project.
The way I tend to handle it for larger projects is to have a separate namespace called Project.Entities which contains my Entity Framework data models. My Project.Models would contain models which use the Entities as a backing store for their data, and provide common methods (Where necessary) to manipulate that data. It may not be the best way to do it, but provides the most flexibility, and sticks to keeping data models separate from the backing store which allows more abstraction. For example, you can always switch out the underlying data layer to in-memory storage, another DAL than Entity Framework or whatever else.
For smaller/temporary/test projects, my Entity Framework data models will be straight in Project.Models and used directly as it's quicker and doesn't require so much thought.

No, model is not data access. Model is a buch of classes to hold data, and it generally does not contain code other than, possibly, to verify the assigned values are permitted.
You access data from controllers. In which way you do that is completely up to you and MVC is not concerned.

Model is your view model, not your domain model.
If you want to do DAL activity, I would tend to wrap it in repository/service that can be injected into your controllers.
This stops your controllers getting bloated and also allows you to mock your DAL layer for unit testing the controllers.

Related

Onion Architecture: Should we allow data annotations in our domain entities?

I am looking to implement the Onion Architecture into our ASP.NET MVC application. I understand the need to separate View Models from Domain Entities, however I am finding myself writing redundant code. There is redundant code because my view models and domain entities look exactly the same with the exception that my view models have the [Serializable] data annotation. I need these models serializable because I am using ASP.NET Session State in which the State Server needs objects to be serializable.
I personally feel the domain entities should NOT be serializable because it would then become dependent on a particular technology. However, how can I avoid redundant code?
I should add that my service methods are dependent on these serializable data models.
I would avoid annotating my domain objects with anything persistence or non-domain related. This way, my Domain project wouldn't depend on another layer and I won't have it cluttered with things that aren't relevant to the Domain. While we need to bend the rules, I prefer bending them in a way not involving dependency on a persistence detail.
The point is to keep the layers focused on their purpose because it's very easy to mix'em up and create (in time) the big ball of mud.
In your case, I have the feeling you don't really have a rich domain or it's improperly modeled. It seems you only have data structures and your needs are CRUDy.
If you are certain the app won't evolve to become more complex i.e it will be just data structure manipulations then you can have one model to use them for all the purposes. Basically you can cut corners and use the 'business' model for everything. No need for abstractions and other stuff.
But if you think the app will evolve or they are or will be business rules and processes i.e you'll need to model behaviour as perceived by the business, then it's best to keep things very decoupled, even if at this stage they seem to be identical.
To make it easier, for your view model you can define one (with copy paste) and use automapper to map the business object to the view model one. Other approach maybe that your query service/repository/object could return directly that view model (map the query result to the view model)
Viewmodels can contain domain entities/models. My domain entities are partial classes and all (eventually) inherit from a base entity which is serialized. Since I use my domain models within some of my viewmodels, I use data annotations on the domain models as well. Your domain model library should not depend on/reference anything else (domain driven).
I wouldn't call [Serializable] a data annotation per se, since it's part of the core .Net platform (mscorlib.dll). Data Annotations refers to specific attributes used to perform data validation and other operations in ASP.Net or Entity Framework.
Should an Entity be [Serializable] ? Probably not, but I don't think this attribute is as "adulterating" to your domain layer as other attributes that come from external, web- or persistence-oriented libraries. It doesn't tie you to a particular third-party framework.
The whole "redundant code" issue depends IMO on the type of system you're building. In a genuine DDD application, duplication between Domain entities and View Models will probably not be all that blatant, and the benefits of a separate presentation model will typically outweigh the costs. A good article on that subject : Is Layering Worth The Mapping ?

Adding functionality to my Entity Framework POCO classes

I've built a web application with Entity Framework using POCO.
I'm using these POCO classes as my business objects and not just for persisting data which works fine until...
Now I need to add some logic into these classes to do thing like total up sales, order lines, etc.
Should I add methods to my POCO classes to enable this functionality or leave them purely for persisting data and create some kind of 'processor' whereby I pass in the business objects and get the values I require out.
Is there a best practice for this?
What is the architectural design you are using or want to use?
For example, if these are your domain entities, you should put as much as possible logic in them. If they are merely data containers and you don't have a real architecture in place, your logic would probably in some business component.
So if you provide your question with some more details, we can help you better.

If Entity Framework / DbContext is the DAL / Repository, where does it fit within 3-tier architecture?

I've been reading articles on StackOverflow and other sites all day about best architecture practices and there are just so many conflicting ideas and opinions.
I've finally settled on an approach, but I am having a really hard time deciding where to place the EF objects (DbContext, Fluent APIs, Seeding data, etc). Here is what I currently have:
ASP.NET MVC Project: The actual web project. Contains the standard views, controllers and View Models (inside a Models folder).
Domain Model Project: Contains all POCO classes that define the database (domain) objects. Currently, does not mention or reference any EF objects.
Service Layer Project: Contains service objects for each type of domain object (e.g., IProductService, IOrderService, etc). Each service references EF objects like DbSets and handles business rules - e.g., add a Product, fetch a Product, append a Product to an Order, etc.
So the question is, in this configuration, where do EF classes go? Initially I thought in the Service Layer, but that doesn't seem to make sense. I then thought to put them in the Domain Model Layer, but then it ties the Domain Models to EF, which is essentially a DAL / Repository. Finally, I thought about creating a separate DAL Project just for EF, but it seems like a huge waste considering it will likely have 3-4 files in it (DbContext and a few other small files).
Can anyone provide any guidance?
There is no need for Domain Model since it will be redundancy. EF classes directly can act as Domain Model and they are converted to View Models while sending it to View. EF can be separated into different class library. Most of them use repository pattern along with any ORM incase it would be easy if they go for replacement. But I've seen criticism over using repository pattern, check this out.
Here is what I do:
Data:
Has one class inheriting from DbContext.
It has all the db sets.
Overrides OnModelCreating.
Mapping primary keys and relationships.
Entities:
Has every POCO classes.
Each property is decorated with needed data annotations.
Services:
Each service has common methods (GetList(), Find(), Create(), etc.).
Business:
Called from clients, orchestrate using services to perform a specific task UserChangePassword (this will check if this can be performed, then perform the task, or return error/unauthorized statuses among many others to make the client shows the correct information regarding the task. This on my case is where I log.
Clients (Desktop/Web/Wpf/etc).
I'm not saying this is the best approach, I'm just sharing what's been working for me.

What is Model in user interface design patterns like MVC, MVP, MVVM?

I have seen lots of tutorials and examples using Model-View UI design patterns, and they all implement them pretty differently, especially the Model part. In some examples Model is data (actual object representation of some DB) in some it's data access layer (like repository pattern) in some it's service layer...
If someone tells you he is using MV* pattern in his app, what will it tell you about app design? Does it maintain in-memory representation of database in object graph and use it as data source or some data access layer to query data base...
What you will choose as a Model for data oriented smart client app containing mostly Tab Pages with Tables?
The word model is used in, at least, two senses. There is your domain model. Here the sense is how you represent your data. There are many ways to structure your data and also many ways to access it. When we talk about the model in this sense we're not particularly concerned with how you are accessing the structures that make it up, i.e., the data access or persistence layer, although you may also hear people speak of the model of persistence. By this, people mean the particular philosophy that the persistence implementation uses, such as ActiveRecord or Repository. You might also hear these referred to as patterns.
Finally, the word model has a very specific meaning in MVC, MVP, and MVVM in the context of a view. In that context it means that particular data object associated with a view, the view model. This could be one of your domain objects, but more typically it is a view-specific object that encapsulates data from one or more domain objects along with ancillary data such as user data that is used by a particular view.
For your application, choose the persistence model that best suits your development environment and language -- LINQ to SQL, LINQ to Entities, nHibernate, Castle ActiveRecord, etc. in the MS world Create view-specific models (classes) for each of your views that hold the data needed by that view. Use your controllers to query your domain model to extract the information needed by the view and map that onto the view model.
If someone says, he is using MV* pattern, it means the application is split into several parts, acting without a direct reference to a specific type, it doesn't say anything about the actual implementation. MVVM means, you have a Model, a ViewModel and View part, that's all.
The model is your data storage. This doesn't say anything of the implementation of it, it can be anything, depending on the task at hand. However, it should be accessed using interfaces, so you can quickly exchange the implementation. That, in a sense, is the whole point of the MVVM pattern - decoupling of the three tiers via interfaces.
Your description sounds alot like my project at the moment - I use sqlite as backing storage with Entity Framework as ORM. However, I also use T4 to generate Dto objects which then get mapped via automapper in the ViewModel, as those only need the data, not the persistance.
The model typically refers to the data layer, but as I discovered, in MVC this can be a little msleading when implementing an ntier approach. The reason for this is that the model is not contained in it's own assembly.
Here is some of very useful feedback I got to a similar question Confussion over MVC and entity model
A model can be considered as data container that facilitates rendering presentation component and/or persisting data to/from data source (i.e. database etc). Besides the data container elements, a model may or may not contain behavior, depending on design context of corresponding architecture.
While the term “Model” is frequently discussed and used in Model-View-Controller pattern context, it is one of most important consideration in current world of software architecture
You may want to look the following article where few popular and new design patterns that are related to presentation component and model are described.

Three tier architecture question

I have an ASP.NET app with a three layer architecture:
Presentation layer: ASP.NET
Bussiness Layer: C# library.
Data Access Layer: C# library with
ADO.Net Entity Framework objects.
Some methods on Bussiness layer would return ADO.NET entity objects but, data access layer is not visible at Presentation layer I can't do that.
My question is: On a design view, Is it correct to expose Entity Objects in the Presentation Layer? I think I only have to link Data Layer library with ASP.NET app.
Thank you!
It's absolutely desirable to have your entity objects available for use and consumption in your presentation tier. That's what all the work is for.
Binding collection of objects to a grid/listview/dropdown
Splashing a single object (i.e. customer) onto a form for read/update/delete
This makes your life easier by far. Otherwise you'd have to pass string after int after double after string between your presentation and business layers.
These may be Entity objects or even your own POCO objects that were hydrated from the Entity objects.
I would even go so far as to say that your Entites should be in their own assembly separate from the DAL.
I suggest that you look into the concepts of View objects...or Data Transfer Objects (DTO). You might consider using a tool like AutoMapper or similar which will create a view specific domain object out of your entities. In general you may have screens that need an entity present to perform its work. But more often than not you will need to pass several different entities. In this case you are better off creating one DTO that contains all of these entities. By doing this you are adding a layer of separation between your presentation layer and your business layer. Often times your entities have more power than you might want to expose to your presentation layer. And...vice versa. Frequently you may need to get some UI messages out to the presentation layer based on some validation flagged in your business layer. Rather than make your ui more complex than it needs to be (by passing in your full entities) you can only pass in what the UI needs in the form of the DTO. Also, there is never a need for your business objects to care about anything specific to the presentation layer. I suggest that you not databind directly to anything as far back as the data access layer. Technically your presentation layer should know as little as possible about your business layer. In the case of MVP or MVC this is very easy to achieve by disconnecting the front end and the back end by way of this additional separation!
I think no, it is not, the best way to do that is to separate data classes from behavior, and reference only data classes in presentation level.The good approach I think to use WCF see this link
See Supervising Controller and Passive View
If you pass the Entity, you are essentially Supervising controller. Otherwise you are Passive View.
Supervising controller is less work, but less testable. Supervising Controller also says databinding is OK.
Passive view is testable but a LOT more work. No databinding. Lots of properties.
Typically I stick with Supervising Controller. You typically don't need that level of testability and it isn't worth the extra trouble.

Categories

Resources