asp.net mvc 4 - loosing dataAnottation when upload model from database -


i have big database existing database comunicate with, , i'm using ef 5.0 database first, problem i'm having if create data decoration [stringlength(50)] on class , databases uploaded, when "upload database" data annotations gone. how can keep them?

it's simple: you can't! because codes auto-generated , on written on each model update or change.

however can achieve need through extending models. suppose ef generated following entity class you:

namespace yoursolution {     using system;     using system.collections.generic;      public partial class news     {         public int id { get; set; }         public string title { get; set; }         public string description { get; set; }                 public int userid { get; set; }          public virtual userprofile user{ get; set; }     } } 

and want work arounds preserve data annotations , attributes. so, follow these steps:

first, add 2 classes (wherever want, it's better in models) following:

namespace yoursolution {     [metadatatype(typeof(newsattribs))]     public partial class news     {          // leave empty.     }      public class newsattribs     {                     // attribs come here.     } } 

then add properties , attributes want second class - newsattribs here. :

public class newsattrib {     [display(name = "news title")]     [required(errormessage = "please enter news title.")]     public string title { get; set; }      // , other properties want... } 

notes:

1) namespace of generated entity class , classes must same - here yoursolution.

2) first class must partial , name must same ef generated class.

go through , attribs never been lost again ...


Comments