MVC, Entity Framework, Business Logic - asp.net-mvc

Although I believe I have a good grasp on MVC (from Rails), I'm learning the "MS Way" with ASP.NET MVC.
Also, I am learning Entity Framework as well.
I've created an Entity called User in my Models folder. Using LINQ to EF I can retrieve records and all is good.
Now, I want to put some business (or what I call, domain) logic in. But in my mind, EF is more of the DAL. So I created a folder called "Domain" and in there, I created a class for some business rules.
One of them is to encrypt passwords.
So I can use the following in my controllers:
string password = Domain.User.EncryptPassword(string salt, string password);
Also, that means the domain logic can access the EF User when it needs to persist to the DB.
Is this logic sound?
Any recommendations appreciated.
Thanks!

The only thing I would ask is: "Why would a user, a person, know how to encrypt or hash a password?"
Encrypting a password would be part of an Application layer. This is almost anti-DDD.

It depends a bit on the project, but generally we:
do not put any code in the EF models, all models are stored in a seperate project
place a business layer between the MVC code and EF. In previous versions of EF this would be used to map EF objects to domain objects, but with POCO this is no longer needed. Any caching would be done in this layer.
use a helper or utility class for encryption

I think what you are looking for is POCO (Plain Old CLR Objects). In one hand you have your EF entities. In the other hand you have your Domain or Business Entities... and then you can map them... your DAL Layer must return POCO entities and not EF entities.. at least that's how is made in a 3-tier application. I suppose it's the same approach in a MVC application...
Am I right?

Related

asp.net mvc with entity framework database first domain model validations

I'm Developing ASP.NET MVC Web Application project, and I'm using Entity Framework Database First Approach, So I would like to make validations on generated model classes, I know if i make validations on them directly, then my model validations will be overwritten every time my domain models are regenerated.
So I made a research, and found two approaches to use for this scenario:
1- Using buddy classes (How to add validation to my POCO(template) classes).
2- Using ViewModels and Auto-mapping them to my Entities (Designing an MVC repository using ViewModels
I see some sort of redundant code in these two methods, so, my question is:
Which one of the two approaches is best to flow?
1) This is the correct solution for adding validation metadata for the Entity Framework objects. The validation will be triggered automatically by EF before calling SaveChanges()
2) This is an aproach for creating Data Transfer Objects from your EF objects. You normally do this when you want to return the objects to the client (like in JSON format) - and you don't want to expose all the EF specific properties (like navigation properties, primary keys etc)

Mapping Domain Models to View Models

I'm starting from a point very similar to: Domain Entities, DTO, and View Models.
The advised use of DTOs to map between the domain model and the MVC's ViewModel seems consistent expectations. I seek details of how to bridge the domain model (Entity Framework-based project) to the WebAPI mvc project.
I'm starting with a project of simple POCOs (generated by EF PowerTools to reverse engineer my existent db) that I want to connect to an MVC4 WebAPI project.
I expect I'll be adding business logic to the baseline POCO project as my solution evolves and perhaps this is the crux of this issue. The business logic that transforms the POCOs into something that can be mapped to the MVC project.
Exactly how do I wire these projects together so i can start creating controllers in the MVC project that knows about the entities of the EF project? Automapper? Can we point to posts/docs where this specific feature of Automapper is employed?
You don't want controllers that knows about the EF entities - that's the whole point of this. :)
You yourself say that the DTOs should be used to map your domain to your view model, and then you ask "how can I bridge my domain model with the mvc controllers?". You've already answered this - with DTOs!
The DTO serves as a transport layer between complex business objects and models used to display a certain view. Both of these have special requirements that don't strictly relate to "just data" - hence using DTOs will give you a greater decoupling and separation of concerns.
If you don't decouple domain from view model, you will be forced to directly reference your EF objects in your view model code, which exposes unnecessary data and functions "up the chain".
Now, if you use WebAPI as a way to ship data then I think you could usually get away with sending the DTOs, since WebAPI data usually wouldn't be implementing view model logic. But YMMV of course, depending on how you plan to use your controllers.
For AutoMapper I'd say it's best to start with their own docs (they even use DTO examples in them): http://github.com/AutoMapper/AutoMapper/wiki/Getting-started

Abstracting the accountcontroller MVC

How would I go about abstracting the membership information in MVC3 c#
Currently the membership data is kept on a localhost SQL server and is linked to MVC via the Entity Framework.
As I want to perform some extensions, I need to abstract it, creating an interface and class for each entity in the SQL database?
Where would I start? Are there any examples available? I can only find ones that are out of date or irrelevant
I think you can rearrange your application, introducing a service layer separated from your presentation layer. The object model (domain model) that you define in the presentation layer for User and other entities should be distinct from the EF data model, so you need only that some sevices ( for example you can implement these as Web Services) read the data using EF and populate your domain model of the presentataion layer.
This approach allows your application to be more flexible to future changes or extensions.

How can I extend the Model in ASP.NET MVC and Entity Framework?

In my first ASP.NET MVC applications, the model was a simple O/R mapping between a table and the classes, managed by the Entity Framework.
Now I would like to add some meat to this skeleton, and introduce business methods for the generated classes. What is the recommended approch to this in ASP.NET MVC (with Entity Framework)? My favorite would be solution which also can be used in a service layer, with no ASP.NET MVC references, so that the same domain logic also could be reused in a desktop client.
Technically, I think it should be possible to extend the generated classes in a way which preserves the additional business logic even if the O/R classes need to be refreshed. (This is more a question related to the Entity Framework however.)
Edit: Many thanks for the contributions, and the information about the next version of Entity Framework (4.0). Building two sets of classes, one auto-generated to represent the data in the persistency layer and one for the actual business logic sounds interesting.
Within MVC.Net, the model is the least clearly defined part. In my opinion, it's basically the rest of your application (i.e. anything not related to the View or the Controller). The O/R Mapping part of your application should probably be outside of the "Model" also, as this is more of a data layer. The Model, should really deal in business objects and create views of your data to pass to the View.
There are lots of differing opinions on this, but I think it's best not to think of MVC.Net as traditional MVC Architecture.
If you are using EF v1.0 right now, the Entity Framework is very intrusive into your application, which means that you cannot create POCO very easily. The way you can extend your model is by using the partial class. So when you refresh your model, the partial class you did will still be valid. The Entity Framework team realizes this is a problem , and have improved this in next version (EF V4.0).
NHibernate is much more friendly and allow you easily extend your business logic.
I really think this blog post by Jeremy D. Miller is very good at pointing out the problem.
Abstract your Business Layer out into another project, then pass an instance of it onto your mvc controller using something like structure map. You can then call this Business Layer from your controller to retrieve your business entities (Model) and pass them on to the UI. This will allow you to resuse your Business Layer in your desktop application.
Not only meat but also some clothes and a style could be added to this project to make it seem chic. It depends on the time you have for the project. If you have time, I could suggest you to get a look to TDD and the frameworks that could be used with TDD such as Castle, NUnit, Moq etc.
As you mentioned a service layer is a must for any project but with these kinds of frameworks you could design your architecture more robust.

Where should my models live? Web tier or Data tier? (MVC + NHibernate)

I am setting up an n-tier application with MVC, Ninject, and NHibernate (my first using these technologies). For clarity's sake, the tiers are a "Data" tier, a "Services" tier, and a "Web" tier (all are separate projects).
With MVC, you have your models that are in the "Models" folder. It seems necessary to put my models here to create strongly-typed Views and to generally keep with the philosophy of MVC.
However, with NHibernate, I also need my models in the "Data" tier so that the mapping can take place and that NHibernate can instantiate actual objects to return to the services layer.
Duplicating the classes across projects is not very DRY and abstracting them into their own library doesn't seem to play well with MVC (neither in practice nor philosophy).
Any thoughts? How do you structure your O/RM objects vs MVC models?
I keep Entity Framework models/classes in the data tier and use the Models folder of the MVC project for presentation models and model binders.
The Data Model is it's own thing. The Model in MVC is something different. It's the model of what you're going to display, which may or may not be your Data Model. You're Data Model may transcend layers, or not.
Take for instance the standard sign-up form. The Data Model may include the username, password and an array of login history classes, a flag indicating it's active and much other stuff. The model in MVC, may only really care about username and password, and that the user type the password twice. Does your Data Model really need two password fields? No. However the model in the MVC does. Hence, two different critters.
I keep all of my models in the data tier because of NHibernate. Take a look at S#arp Architecture for a great way of keeping your presentation clean. Models do not have to be physically located in your web project for your views to be strongly typed.
You are right about the DRY principle here. I keep my LINQ-to-SQL objects separated from my business objects and I have some duplication and it doesn't make me feel good but it seems there isn't a simple workaround this..
I had a tough time making this decision but I watched Rob Conery's blog while building the MVC Storefront and in the end I decided to go this way (ORM objects AND business objects)
With MVC, you have your models that
are in the "Models" folder. It seems
necessary to put my models here to
create strongly-typed Views and to
generally keep with the philosophy of
MVC.
No model can be anything you want. I would still use a presentation model if it were necessary but I have no objection to using your nhibernate entities in your views.
With NHibernate you don't really need a Data Tier since the Session itself is the data tier.
The service tier seems like a valid idea but only if you plan on having multiple client for this layer.
Otherwise, I would only have 1 project and use namespaces to separate my layers. It builds faster and is easier to deploy.

Resources