Asp.net-Mvc-4

從數據庫上傳模型時失去數據註釋

  • February 15, 2022

我有一個大型數據庫現有數據庫要與之通信,並且我首先使用 EF 5.0 數據庫,我遇到的問題是,如果我[stringlength(50)]在類上創建任何數據裝飾,然後上傳數據庫,當我“上傳從數據庫”所有數據註釋都消失了。我該怎麼做才能保留它們?

這很簡單:**你不能!**因為這些程式碼是自動生成的,並且會在每次模型更新或更改時被覆蓋。

但是,您可以通過擴展模型來實現您所需要的。假設 EF 為您生成了以下實體類:

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; }
   }
}

並且您想要做一些工作來保留您的數據註釋和屬性。因此,請按照以下步驟操作:

首先,在某個地方(無論你想要什麼,但最好是在Models)添加兩個類,如下所示:

namespace YourSolution
{
   [MetadataType(typeof(NewsAttribs))]
   public partial class News
   {
        // leave it empty.
   }

   public class NewsAttribs
   {            
       // Your attribs will come here.
   }
}

然後將您想要的屬性和屬性添加到第二類 -NewsAttribs這裡。:

public class NewsAttrib
{
   [Display(Name = "News title")]
   [Required(ErrorMessage = "Please enter the news title.")]
   public string Title { get; set; }

   // and other properties you want...
}

筆記:

1)生成的實體類的命名空間和你的類必須相同——這裡YourSolution

2)您的第一個類必須partial並且其名稱必須與 EF 生成的類相同。

經歷這個,你的屬性再也不會失去了……

引用自:https://stackoverflow.com/questions/17744625