为实体框架生成的类添加数据注解 [英] Add data annotations to a class generated by entity framework
本文介绍了为实体框架生成的类添加数据注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下实体框架生成的类:
I have the following class generated by entity framework:
public partial class ItemRequest
{
public int RequestId { get; set; }
//...
我想将此设为必填字段
[Required]
public int RequestId { get;set; }
但是,因为这是生成的代码,所以会被清除.我无法想象创建分部类的方法,因为该属性是由生成的分部类定义的.如何以安全的方式定义约束?
However, because this is generated code this will get wiped out. I can't imagine a way to create a partial class because the property is defined by the generated partial class. How can I define the constraint in a safe way?
推荐答案
生成的类 ItemRequest
将始终是 partial
类.这允许您编写标有必要数据注释的第二个分部类.在您的情况下,部分类 ItemRequest
将如下所示:
The generated class ItemRequest
will always be a partial
class. This allows you to write a second partial class which is marked with the necessary data annotations. In your case the partial class ItemRequest
would look like this:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
//make sure the namespace is equal to the other partial class ItemRequest
namespace MvcApplication1.Models
{
[MetadataType(typeof(ItemRequestMetaData))]
public partial class ItemRequest
{
}
public class ItemRequestMetaData
{
[Required]
public int RequestId {get;set;}
//...
}
}
这篇关于为实体框架生成的类添加数据注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文