ef5数据库第一个数据注释 [英] ef5 database first data annotation

查看:118
本文介绍了ef5数据库第一个数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VS2012启动MVC4。我也将EF5与创建类的数据库优先方法一起使用。

I am starting MVC4 with VS2012. I am also using EF5 with the "Database First" method of creating my classes.

但是,由于可以重新生成生成的眼镜,因此我无法放置数据注释详细信息来协助

However because the generated glasses can be regenerated I cannot put the Data Annotation details to assist with validation.

我已经看到了一些使用MetaData和部分类的代码片段,但我想知道是否有人知道一个小的可编译示例,我可以看看并拆开。

I have seen some code snippets that use MetaData and partial classes but I was wondering if anyone knows of a small compilable example that I can look at and pull apart to better understand how the vasious classes interlink.

非常感谢您的帮助。
Dave

Many many thanks for any help. Dave

推荐答案

您可以通过扩展模型来实现所需的功能。假设EF为您生成了以下实体类:

You can achieve what you need through extending models. Suppose that EF generated the following entity class for you:

namespace YourSolution
{
    using System;
    using System.Collections.Generic;

    public partial class News
    {
        public int ID { get; set; }
        public string Title { get; set; }                  
        public int UserID { get; set; }

        public virtual UserProfile User{ get; set; }
    }
}

,您想做一些变通的事情来保存您的您的数据注释和属性。因此,请按照以下步骤操作:

and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:

首先,在需要的任何地方添加两个类(无论您想要的是什么,但最好使用 Models ),如下所示:

First, add two classes some where (wherever you want, but it's better to be in Models) like the following:

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

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

然后将要添加的属性和属性添加到第二个类- NewsAttribs 此处。 :

then add what properties and attributes you want to the second class - NewsAttribs 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

1) The namespace of the generated entity class and your classes must be the same - here YourSolution.

2)您的头等舱必须 partial 及其名称必须与EF生成的类相同。

2) your first class must be partial and its name must be the same as EF generated class.

请仔细阅读此内容和您的属性再也不会丢失...

Go through this and your attribs never been lost again ...

这篇关于ef5数据库第一个数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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