将数据注释添加到由实体框架生成的类中 [英] Add data annotations to a class generated by entity framework
问题描述
public partial class ItemRequest
{
public int RequestId {get;组; }
// ...
我想让这个必填字段
[必需]
public int RequestId {get; set; }
但是,因为这是生成的代码,所以将被清除。我无法想象创建一个部分类的方法,因为属性是由生成的部分类定义的。
生成的类 ItemRequest
将永远是一个 partial
类。这允许您编写一个第二个部分类,其中标有必要的数据注释。在你的情况下,部分类 ItemRequest
将如下所示:
using System.ComponentModel;
使用System.ComponentModel.DataAnnotations;
//确保命名空间等于其他部分类ItemRequest
命名空间MvcApplication1.Models
{
[MetadataType(typeof(ItemRequestMetaData))]
public partial class ItemRequest
{
}
public class ItemRequestMetaData
{
[必需]
public int RequestId {get; set ;}
// ...
}
}
I have the following class generated by entity framework:
public partial class ItemRequest
{
public int RequestId { get; set; }
//...
I would like to make this a required field
[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?
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屋!