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 autogenerated, so from I what I understand, changing them is a bad idea (and will get written over anyway if the the database model is refreshed).
A seperate metadata class can be created to provide the attributes:
//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;
}
Marked as answer by thorma04 on Dec 27, 2012 06:06 PM
thorma04
Member
26 Points
51 Posts
Adding Validation Attributes With an Entity Framework Data Model
Dec 27, 2012 04:26 PM|LINK
Hello,
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 autogenerated, so from I what I understand, 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?
bvsskiran
Member
218 Points
38 Posts
Re: Adding Validation Attributes With an Entity Framework Data Model
Dec 27, 2012 05:15 PM|LINK
Create A Model, which matches your DB Table or View, Or you can use the T4 Templates for model generations from your Database.
if you need more info on T4 templates,
check the link http://msdn.microsoft.com/en-us/data/gg558520.aspx
thorma04
Member
26 Points
51 Posts
Re: Adding Validation Attributes With an Entity Framework Data Model
Dec 27, 2012 06:05 PM|LINK
A seperate metadata class can be created to provide the attributes:
//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; }