定义数据库中的第一种方法使用的DbContext与ObjectContext的数据注解 [英] Defining data annotation using DbContext versus Objectcontext in the database first approach

查看:210
本文介绍了定义数据库中的第一种方法使用的DbContext与ObjectContext的数据注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架数据库的第一种方法,当我习惯使用的ObjectContext的数据库表被映射的默认模板的工作,所以我用来创建#partial类放大器&; [MetadataType(typeof运算)应用数据注解,,但是当我开始使用的DbContext code生成模板来映射数据库中的表,我发现,它会在我的示范区创建文件夹.TT是我发现的我可以直接申请数据标注到的.cs类本身,而无需创建分部类在ObjectContext的情况下
目前的数据注解是做工精细,, ,但会我的做法使我的问题我不知道,我应该创建部分类为我所用的ObjectContext 办?
BR

I am using the database first approach with entity framework, when i used to work on the default template the database tables were mapped using the ObjectContext, so i used to create #partial classes & [MetadataType(typeof ) to apply the data annotation ,, but when i start using the Dbcontext code generation template to map the database tables i found that it will create .tt folder in my Model area were i find that i can apply the data annotation directly to the .cs classes themselves without the need to create partial classes as in objectcontext case. Currently the data annotations are working fine,, but would my approach cause me problems i am not aware of and i should create partial classes as i used to do with the Objectcontext ? BR

推荐答案

在一般情况下,你应该编辑生成的code,因为您更改将在重新生成被改写。这就是为什么大多数的发电机发出的部分课程。

In general, you shouldn't edit generated code because changes you make will be overwritten on re-generation. This is why most generators emit partial classes.

您的情况最好的做法是在与另一部分类声明的解决方案来创建一个新的文件。在该文件中,添加<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx\"><$c$c>MetadataType属性类,并添加属性级别的属性验证的哥们类(一个在属性中引用)。这允许您使用上生成的属性属性验证,并应你的模型/数据库更改,仍然可以重新生成模型类,而不会失去他们。

The best practice for your situation would be to create a new file in your solution with another partial class declaration. In that file, add the MetadataType attribute to the class, and add your property-level validation attributes to the "buddy" class (the one referenced in the attribute). This allows you to use validation attributes on the generated properties and, should your model/database change, you can still re-generate your model classes without losing them.

例如,您的新文件可能看起来是这样的:

For example, your new file might look something like:

[MetadataType(typeof(PersonMetadata))]
partial class Person
{
    // Add logic to the generated class in here.

    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
}

class PersonMetadata
{
    // Add attributes to the generated properties in here.

    [Required]
    public string FirstName { get; set; }
}

这篇关于定义数据库中的第一种方法使用的DbContext与ObjectContext的数据注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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