ASP.Net Core and model validation - asp.net

Suppose I have a model which I need to validate. I can add some validate attributes to the properties I want to validate. And it works pretty fine. But at some point I want to validate this model depending on other models (I will need t query db). And here there are some options.
create a special validate attribute which will lack dependency injection
delegate this validation to some business layer (manager) and in controller
_
if (Model.IsValid) {
if(!await Manager.Create(myModel)) {
Model.CopyErrors(Manager.Errors); // Extension method for Model
}
}
So what is the correct way of handling such a situation?
P.S. I am using asp.net core and entity framework core

What you need is Fluent Validation

Related

entity framework core exception handling db first

Background
With ef core code first approach, validation is robust and simple: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation
With the database first approach, it seems like any validation is happening behind the scenes by the database when dbcontext.SaveChanges(); is called. What's worse, these exceptions are nebulous and entirely unhelpful, for example, SqlException: String or binary data would be truncated can be thrown if any of the string properties of any of the entities have too many chars (ours is a legacy app riddled with char(10) and such), or even if a key that is a string is left null.
Question
I want to know if there is any reasonable or accepted way of enforcing the validation. I've found this question which might help debugging, but I would like to enforce the constraints in code
Is there any better method than changing every auto property to one that throws if it's constraints aren't met?
EntityFramework Core does not enforce any validation at all. The validation rules you see in the example are enforced by MVC and not EF. One of the main reason for EF Core to remove validation check was that only. Validation are run in UI and then in EF and then again in database which is just redundant. Hence client side validation is left to the front-end (MVC in this case) and server side is done by database engine.
When you use database first approach, EF core does not generate any annotation for validation because it does not reason about them anyway. That means you would get only server side validation which means error during SaveChanges.
The only way to enforce constraint in the code (client side) is to write those annotations so that MVC can enforce them or write custom code to deal with it. The whole validation mechanism is transparent to EF.
I ended up going with a psuedo extension to the generator tooling. Since the DBContext is a partial class, I made a new class that has a main
public partial class DBContext{
public static void Main(string[]args){
DBContext context = new DBContext();
var modelbuilder = new Microsoft.EntityFrameworkCore.ModelBuilder(new Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet());
context.OnModelCreating(modelbuilder);
IMutableModel model=modelbuilder.Model;
from there I used Linq to transform the various info about each entity's properties and the annotations on them into List<KeyValuePair<string,List<KeyValuePair<Regex,string>>>> where the first pair's key is the entity name, and the value is a list of find and replace pairs to edit the code that had already been generated with the corresponding validation, one per property. Then all I had to do was abuse the fact that the tooling generates the classes in <className>.cs files, and iterate over my list, executing the replacements for each entity source code file.
I'd have preferred doing something a little less hacky, because I'm relying on format that the ef tooling outputs, but it works

Asp.net MVC 5 model validation regex not validating special characters

I have using ASP.NET MVC 5 and for validation I am using the regular Jquery unobtrusive validation library.
Currently I am facing an issue, The regular expression validation is working all right on client side but on server side its not validating the value.
[RegularExpression(#"^[0-9]{19}$", ErrorMessage = "Invalid Value")]
public string Value{ get; set; }
this is the simple regular expression to validate 19 digits. Its working fine on client side it'll now allow ' or - or any thing to pass on but if i submit directly to server than the model is not being validated.
Do I need to do some thing special?
ModelBinding ( the process of mapping post/get values to a complex model) occurs when you send data via post/get/put/delete requests, if you are manually creating a class with validation classes somewhere those data/validation annotations won't apply.
you can validate models manually - Validate list of models programmatically in ASP.NET MVC
That said, there is a library called PostSharp that can enforce those rules even when you are creating custom object/models outside of MVC ( CodeContracts ) and if it doesn't validate it throws an exception. Keep in mind that this library is paid but it has free version available that might fit your needs.

ASP.Net , data validation should be in the controller, not the model, contrary to this tutorial example?

I am following ASP.NET MVC Music Store Tutorial by Jon Galloway Microsoft from http://mvcmusicstore.codeplex.com
While setting up this fictitious music store , we have Album.cs as the model with these lines of code
public class Album
{
[Required(ErrorMessage = "An Album Title is required")]
[StringLength(160)]
public string Title { get; set; }
//.......More code follows
What I find confusing is, why is the validation being done here by the Required attribute in the model, instead of the controller? Isn't the controller supposed to do the validation? or is that standard practice to do the validation in the model...suppposedly the tutorial is from microsoft?
Thank you
What I find confusing is, why is the validation being done here by the
Required attribute in the model, instead of the controller
Actually that's the domain model and it should have domain validation on it in order to ensure that it will stay consistent. On the other hand you should have a view model being exposed to the views on which perform view specific validation. And if this domain model will never be reused outside of this application you could rely only on the view model validation.
For example you will see many wrong examples putting view specific data annotation attributes on the domain models such as [DisplayFormat] and [Display]. All those examples are an illustration of bad design in which the domain models are used as view models.
You are using DataAnnotations in the Model that states that the Title field must be filled in before being posted back to the server. In the controller you can also check if ModelState.IsValid however adding the DataAnnotations at the Model level is the correct way to implement data validation.
we generally use Microsoft enterprise library's validation block to validate in the controller. Which enable us to add or remove validations
easily by modifying config file.

Domain logic in a Entity framework Attribute

I've an ASP.NET MVC project with a domain and a data layer (contains just EF and migrations).
Now, I have to validate a Client's VATNumber field with a specific formula I'm having doubts where to place it.
I would like to use the Controller's ModelState to check if the field is valid, using a EF DataAnnotation ValidationAttribute, so I don't have to validate it in the Controller's Saving Method. But I'm conflicted having to put business logic in the data layer.
Is there some kind of alternative to ValidationAttribute, so it can be "injected"? Or I'm just looking at this wrongly?
Validation attributes is not part of Entity Framework.
If you want splite data layer from presentation layer, you can use Viewmodels and bind them on datamodels with Automapper. In this case you place domain validation on viewmodel and validation of datalayer on datamodel.
In very complicated cases you may have three models: viewmodel, domainmodel and datamodel, but in common cases viewmodel and datamodel is enough.

ASP.NET MVC3 Generate View Model including validation attributes

I am wondering if there is a way to generate a View Model from database table including validation (required,length,datatype). Of course I will edit it and enhance it.Otherwise it is a waste as I have to type in everything
We are implementing a "Dynamic" approach to validation in one of our projects where the validation rules are encoded in a database table and we override GetValidators() in a custom implementation of DataAnnotationsModelValidatorProvider to inject custom and/or standard validation attributes. These can then be propagated to the client if we want them to. As for creating a viewModel from the existing database, you can use t4 files to read the db schema and generate classes for you and inject validation attributes on the model as it is being created.

Resources