Adding Validation Attributes With an Entity Framework Data Model

asp.net-mvc-4 entity-framework

Question

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?

1
24
2/4/2015 5:48:01 PM

Accepted Answer

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;
}
36
4/7/2013 7:33:25 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow