Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Validation Attributes With an Entity Framework Data Model

Tags:

Preface Feb 2015 If you are still using Entity Framework EDMX, please do yourself a favor and checkout using Entity Framework Code First instead. The difference is that your tables are created from your model classes, rather than in EDMX where your model classes are created with your tables. It's an all around easier solution, and the problem in this question doesn't even exist!

Getting Started with Entity Framework 6 Code First using MVC 5

I have an existing SQL database, and I am using ADO.NET Enity Data Model for the model. I am trying to build some CRUD features into my MVC application.

In all the tutorials I have found on the subject, they build the model from scratch and add the attributes to the model class. For example:

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

However, the model classes are auto-generated, so I think changing them is a bad idea (and will get written over anyway if the the database model is refreshed).

How would I add validation attributes?

like image 254
Mason240 Avatar asked Dec 27 '12 18:12

Mason240


People also ask

How do you add validation to a model?

DataAnnotations assembly has many built-in validation attributes. Open Visual Studio 2015 or an IDE of your choice and create a new project. Choose web application project and give an appropriate name to your project. Select the empty template, check on MVC checkbox below, and click OK.


1 Answers

You can create a partial class, separate from the EF generated class, to store the metadata in.

//Contact.cs - The original auto-generated file  [System.ComponentModel.DataAnnotations.MetadataType(typeof(ContactMetadata))] public partial class Contact {     public int ContactID { get; set; }     public string ContactName { get; set; }     public string ContactCell { get; set; } }  //ContactMetadata.cs - New, seperate class  using System.ComponentModel; using System.ComponentModel.DataAnnotations; internal sealed class ContactMetadata {     [Required(ErrorMessage = "Name is required.")]     [StringLength(5)]       public string ContactName; } 
like image 197
Mason240 Avatar answered Sep 25 '22 11:09

Mason240