从数据库上载模型时丢失数据注释 [英] loosing dataAnottation when upload model from database

查看:24
本文介绍了从数据库上载模型时丢失数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的数据库要与现有的数据库通信,我首先使用的是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.
    }
}
然后将您想要的属性和属性添加到第二个类中--此处。:

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生成的类相同。

通过此操作,您的属性将再也不会丢失...

这篇关于从数据库上载模型时丢失数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆