Add data annotations to a class generated by entity framework

P.Brian.Mackey picture P.Brian.Mackey · May 24, 2013 · Viewed 61.5k times · Source

I have the following class generated by entity framework:

public partial class ItemRequest
{
    public int RequestId { get; set; }
    //...

I would like to make this a required field

[Required]
public int RequestId { get;set; }

However, because this is generated code this will get wiped out. I can't imagine a way to create a partial class because the property is defined by the generated partial class. How can I define the constraint in a safe way?

Answer

MUG4N picture MUG4N · May 24, 2013

The generated class ItemRequest will always be a partial class. This allows you to write a second partial class which is marked with the necessary data annotations. In your case the partial class ItemRequest would look like this:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

//make sure the namespace is equal to the other partial class ItemRequest
namespace MvcApplication1.Models 
{
    [MetadataType(typeof(ItemRequestMetaData))]
    public partial class ItemRequest
    {
    }

    public class ItemRequestMetaData
    {
        [Required]
        public int RequestId {get;set;}

        //...
    }
}