asp.net-mvc-4 - 从数据库上传模型时丢失dataAnottation

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

我有一个现有的大型数据库要通信,并且我首先使用的是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)生成的实体类和您的类的 namespace 必须相同-这里为YourSolution

2)您的第一个类必须partial,并且其名称必须与EF生成的类相同。

经历这个过程,您的属性再也不会丢失...

关于asp.net-mvc-4 - 从数据库上传模型时丢失dataAnottation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17744625/

相关文章:

c# - 使用 Ninject 将通用接口(interface)绑定(bind)到存储库时获取 "MissingMethodException: Cannot create an instance of an interface"

c# - @ 后有 2 个字符的正则表达式电子邮件

json - MVC 4 Web API - 自定义对象的 JSON 序列化

entity-framework - DbContext.Entry 附加实体

javascript - 如何仅使用带有 angularjs 的选项卡打开不同的不同 View html 页面

c# - 一个实体可以与多个实体相关联吗?

asp.net-mvc - Asp.Net MVC : Some un-localized default error message?

c# - 自定义验证属性 MVC2

jquery - mvc post 与 ajax 效果

asp.net-mvc-4 - OAuthWebSecurity.VerifyAuthentication IsSuccessful 返回 false 如何确定原因?