【问题标题】:loosing dataAnottation when upload model from database从数据库上传模型时丢失数据注释
【发布时间】:2013-07-19 11:08:00
【问题描述】:

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

【问题讨论】:

  • 我更新了我的答案,向您展示如何...

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


【解决方案1】:

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

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

通过这个,你的属性再也不会丢失了......

【讨论】:

  • 我最终按照本教程进行了类似的操作msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx
  • 很棒的例子 - 我的主要错误是命名空间不一样。希望我早点找到这个例子!希望这个帖子的标题更好更容易找到。扩展部分类并将 DataValidation 添加到 MVC。很好的答案。谢谢。
【解决方案2】:

接受的答案可能适用于标准数据操作,但我正在尝试在调用 DbSet.Add 之前使用 TryValidateObject 验证模型。有了接受的答案,它仍然没有接受数据注释。

我在 .NET 运行时 GitHub 线程中发现了对我有用的东西,正如我所推断的那样,是 .NET 开发人员之一。

基本上,这是一个错误,您必须强制模型使用 TypeDescriptor.AddProviderTransparent 识别元数据装饰。 . .

TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(News), typeof(NewsAttrib)), typeof(News));

一旦我进行此调用,TryValidateObject 会识别数据注释并在不满足任何约束时返回 false

这是链接。我还不到一半,在 .zip 文件中有一个工作代码示例。

https://github.com/dotnet/runtime/issues/46678

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多