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

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)

Related

What is the best practice, Entity Framework Models or MVC Models?

When using Entity Framework with Code-First, what is the best practice when calling database data?
This is my first time using Entity Framework with MVC and noticed that it automatically builds Models in my DataLayer. I also have the basic Models within my MVC UI which allow me to manipulate and display the data within my Views. I currently grab the data using my Workflow layer, and then AutoMap the Database Model to my UI Model to display the data.
Is this the best practice? Should I be using the Entity Framework Models instead of my UI Models? Or this even possible to do cleanly?
Any information on the matter would be appreciated.
It's up to you really. If you like to re-use the same EF entities for your view models as well; go ahead. Personally, I prefer not to. This is because you normally end up adding a bunch of properties to the class that have nothing to do with what's stored in the data and yes; I know you can use the NotMapped attribute like this:
[NotMapped]
public string MyExtraProperty { get; set; }
but I prefer not to. Additionally, you end up adding [Display] and other attributes to your properties and before you know it, you've got something decorated with both data specific and UI specific attributes and it can get messy if you're not careful.
So for me; I have the following:
Domain Entity
View Model
Service/Facade/Repository
Controller calls repository to get the domain entity and converts it to a view model for displaying.
I find that to be a cleaner approach, but maybe that's just me.. the most important thing is to just choose one way and stick with it for the sake of consistency and clarity of code, but either method is acceptable.. "whatever floats your boat" as they say...
The POCOs created by EF are supposed to be used as your model. The general idea is that you have EF providing access to your database. You query EF using LINQ and/or extension methods and end up with an object or collection of objects that you display on your UI by binding them in WPF. That is of course if you're using WPF as opposed to the older WinForms. I can tell you from experience that it's a very streamlined process once you become familiar with the technologies. That's how a very basic setup would work.
A more advanced way of going about it is adding architectures like Model-View-ViewModel (MVVM) and possibly the repository pattern into the mix at which point you get better separation of code and presentation at the cost of increased complexity.
I don't know what flavor of MVC you're using and how it can be made to intermingle with the above, but if you want to know more about how EF was envisioned to work you should look into the technologies I've listed above.

Passing POCOs or EF objects to the Web project?

Say I have a Visual studio solution with two projects: one web project, and one data project.
Does it really matter whether I pass the EF object from the data project to the web project, or do I need to explicitly define POCOs in the data project to pass to the web project?
It seems to me that needing to create POCOs instead of simply using EF objects adds yet another thing that needs to be done...and I don't particularly see the purpose.
If you're using Entity Framework 4, the EF objects are POCO objects, and so should be used in any situation where your Model matches your EF object (CRUD operations are the typical ones). However there will more than likely be situations whereby the standard POCO object doesn't encapsulate all of the fields that are needed for a View Model (typical ones I have this with are account pages where you have two password fields) and so you will need to create a Model for the page, which then passes the data into your EF POCO objects.
So if you're using DbContext (which creates POCO objects for you) there is no reason not to use those objects.
It's not a good practice to pass the EF objects directly to the web project. As the state changes occurring in the EF objects can directly reflect on the database. Because of this you should explicitly define POC objects for web project.(we can call this as Data Model or simply Model. The POC object used for retrieving data from the View can be called as View Model. In appropriate situations you can use the same POCO class as a Data Model as well a View Model)

MVC3 remote validation on an entity from a refrenced assembly?

If I have an entity class defined in a separate assembly (like from Entity Framework), is it possible to add remote validation to a property?
If the class were defined in my MVC project I would simply add a Remote attribute to the property, but I can't do that when the class is defined in a separate assembly. I do have other data annotations defined in my EF project, but it doesn't make any sense to add a Remote annotation there.
I can probably just add the jquery validation rule to my view by hand, but I'd like to know if there's a way to let the MVC framework do it for me.
Every example I've found on the web assumes you're using an entity defined in your MVC project where it's easy to add remote validation. Is it a mistake to use my EF entities as my model classes in my views? It seems like a waste of effort to make new entities with all the same properties, and all the same data annotations as my EF classes, and have to translate back and forth between the two.
You can use ViewModels in your MVC project and add the remote attribute to your models there or if you are using entities in another assembly why can't you add the remote attribute to properties of those entities? I am not sure I see why it doesn't make sense to do that.
This is definitely a case for a separate view model class. If you want ASP.NET MVC specific features and entities in a separate assembly in the same time you must use a view model. To simplify mapping between the entity and the view model you can use AutoMapper.

MVC, Entity Framework, Business Logic

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?

Working with MVC 2.0 and the Model in a separate assembly

I'm new to MVC and even though there is a lot (and I do mean a lot) of information out there that is very useful - it's proofing very difficult to get a clear understanding on how to achieve my exact requirements with MVC 2.0.
I would like to set up a solution as follows:
Provide a web UI using an MVC 2.0 project.
Use Linq to SQL classes project for data persistence.
I have a two separate code modules that will need to access the above Linq to SQL model - so I won't be able to include my Linq to SQL model directly in the MVC project itself.
Also I have a Business Logic layer in front of my Linq to SQL project.
My questions are:
How do I set up the Model part of my MVC application to point to my Linq to SQL project via my BLL?
How do I perform web app validation? Can I use MVC 2.0 Model Validation? If not what are the alternatives?
Finally (and slightly aside) - What is the ViewModel and how does this differ from the Model?
So many questions. But this is an exciting new technology and data access issues aside, everything else I've got to grips with very quickly and I think MVC 2.0 is fantastic.
Thanks for any pointers you can provide.
How do I set up the Model part of my
MVC application to point to my Linq to
SQL project via my BLL?
Typically you'd use a repository pattern for this. Your controller has a reference to your repository - the repository returns your domain objects from your database. The MVC app has no knowledge LINQ to SQL exists.
How do I perform web app validation?
Can I use MVC 2.0 Model Validation? If
not what are the alternatives?
Put view models in your MVC project. These view models may closely align with your domain models but their concern is to be the presentation model. Put your data annotations for validation on these view models - the MVC framework will automatically ensure validation occurs on these view models decorated with data annotations. It's pluggable so you could use alternatives - but with MVC 2, it's baked in fairly well and this includes client side validation.
Finally (and slightly aside) - What is
the ViewModel and how does this differ
from the Model?
I partially answered this one above. the shape of your domain models may not be the shape you need to display your views - view models are great to bridge this gap. Additionally, even if the shape does match exactly - view models are still a good idea so that you can put UI validation code there and other presentation meta-data on them (since you do not want anything related to presentation logic on your domain model).
Here's link for view model patterns.
Hope this helps.
You can add a reference to the objects exposed from your BLL assembly and use them as your Models.
When you want to add validation to classes that are generated use buddy classes.
A ViewModel is a custom-shaped aggregate of Model data. There is exactly one per View, as the ViewModel's purpose is to surface exactly the data needed by a particular View in a convenient and concise way.
An example might be a View that contains both Order and OrderDetail information. A ViewModel can hold internal references to the repositories and business objects for each type. Properties of the ViewModel merge together the data from these objects.
ViewModels will be useful in your case also because you want your Models to be in a separate assembly. You can apply the DataAnnotations to ViewModel properties for validation. You would make the "raw" business object models internal properties of your ViewModels, and expose public methods to retrieve and persist data.

Resources