从数据库上传模型时丢失数据注释

时间:2013-07-19 11:08:01

标签: asp.net-mvc-4 entity-framework-5 data-annotations ef-database-first

我有一个大型数据库现有数据库可以通信,我首先使用的是EF 5.0数据库,我遇到的问题是,如果我在类上创建任何数据装饰,如[stringlength(50)],那么上传数据库,当我“从数据库上传”时,所有数据注释都消失了。我该怎么做才能保留它们?

1 个答案:

答案 0 :(得分:8)

非常简单:你不能!因为这些代码是自动生成的,并且会在每次模型更新或更改时覆盖。

但是,通过扩展模型,您可以实现所需。假设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生成的课程相同。

通过这个,你的属性再也没有丢失......