Adding Validation Attributes With an Entity Framework Data Model
Solution 1:
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;
}
Solution 2:
Mason240 answer works well, I will try to improve it : you could create a new ContactDataAnnotations.cs class with :
//ContactDataAnnotations.cs - A new file
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(ContactMetadata))]
public partial class Contact
{
// No field here
}
internal sealed class ContactMetadata
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(5)]
public string ContactName {get; set; }
}
This way, you can regenerate your Contact class through EF without touching DataAnnotations - and without warning, by the way.