0

In my application I used Entity Framework generated from a db with ado.net dbcontext generation as well.

The client side works well when there's a not null fk but for the fields line a varchar/nvarchar not null the mvcvalidator just doesn't seem to recognize that the field is should be "required".

Any idea why this happens?

0

1 Answer 1

4

No the Mvc Validator isn't going to read your database metadata and perform client validation.

Typically you would create a ViewModel/DTO and place validations there. Like a product for example, see how the fields have Attributes, these are from the System.ComponentModel.DataAnnotations Namespace and are used to decorate your models with validation constraints.

 public class Product
 {
        public int Id { get; set; }

        [Required]
        [StringLength(10)]
        public string Name { get; set; }

        [Required]
        public string Description { get; set; }

        [DisplayName("Price")]
        [Required]
        [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
        public decimal UnitPrice { get; set; }
    }

See the full example here: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs

You use the model (like above) in your view, mvc will perform the validations, even client side, and then use the returned object instance to fill your entity model.

If you do not want to create separate classes and insist on using Entities from EntityFramework you could create a buddy class.

See this article: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Scroll down to => But what if we are using a graphical tool for our ORM mappings?

There is a Person, and it is linked up with the Validator class by tge MetadataTypeAttribute

Something like:

[MetadataType(typeof(PersonMetaData))]
public partial class Person
{
}
public class PersonMetaData
{
    [Required(ErrorMessage = "Name is required.")]
    public object Name;
}
Sign up to request clarification or add additional context in comments.

2 Comments

yes, I found the same solution. I think Microsoft created a "semi good" object that lacks in some functionalities; I can't see why the entity framework couldn't do all the work as it does for primary and foreign key. Thanks anyway
:) The view-model approach is pretty nice, and kinda decouples you from entity framework. Do consider accepting an answer if you found it helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.