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

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

问题描述

我正在使用数据库第一种方法与实体框架,当我以前在默认模板上工作的数据库表使用ObjectContext映射,所以我曾经创建#partial类& [MetadataType(typeof)来应用数据注释,但是当我开始使用Dbcontext代码生成模板来映射数据库表时,我发现它将在我的模型区域中创建.tt文件夹,我发现我可以应用数据注释直接到.cs类本身,而不需要像在objectcontext case 中创建部分类。
目前的数据注释工作正常,,但是我的方法会导致我不明白的问题,我应该像以前一样使用Objectcontext 创建部分类?
BR

解决方案

一般来说,您不应该编辑生成的代码,因为您所做的更改将被覆盖,代。这就是为什么大多数生成器发出部分类。



您的情况最佳做法是使用另一个部分类声明在您的解决方案中创建一个新文件。在该文件中,添加 元数据类型 属性,并将您的属性级验证属性添加到好友类(属性中引用的类)。这允许您在生成的属性上使用验证属性,如果您的模型/数据库更改,您仍然可以重新生成模型类,而不会丢失它们。



例如,您的新文件可能如下所示:

  [MetadataType(typeof(PersonMetadata))] 
partial class Person
{
//在这里为生成的类添加逻辑。

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

class PersonMetadata
{
//在此处为生成的属性添加属性。

[必需]
public string FirstName {get;组; }
}


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

解决方案

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.

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天全站免登陆