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?
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With