在设置部分类属性的属性 [英] Setting attributes of a property in partial classes

查看:93
本文介绍了在设置部分类属性的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有实体框架(EF)产生的雇员类。

 公共部分类员工
{
私人字符串名称;
公共字符串名称
{
{返回名称;}
集合{名称=值;}
}
}

现在我想把必需属性的名称属性中使用MVC3验证在由我写的其他员工部分类为了延长它是由EF生成的,这样我就不必重写我的代码,如果我刷新由EF生成的模型之一。



我写的部分类在相同的程序集和命名空间。

 公共部分类员工
{
//应该是什么我写这里的名称属性添加必需的属性?
}


解决方案

这实际上是可能只有通过哥们类,但是它是不推荐的方式。你应该让你的验证在自定义视图模式,因为往往你需要不同的看法不同的验证,但你的实体可以只保留一组验证的属性。



哥们类的实例:

 使用System.ComponentModel.DataAnnotations; 

[MetadataType(typeof运算(EmployeeMetadata))]
公共部分类员工
{
类的私有EmployeeMetadata
{
[必填]
酒店的公共对象名称; //类型并不重要,它只是一个标记
}
}


I have an employee class generated by Entity Framework (EF).

public partial class employee
{
    private string name;
    public string Name
    {
        get{return name;}
        set{ name = value;}
    }
}

Now I want to put a required attribute in the name property to use in for MVC3 validation in another employee partial class which is written by me in order to extend the one which is generated by EF so that I don't have to rewrite my code if I refresh the model generated by EF.

My written partial class is in the same assembly and name space.

public partial class employee
{
    // What should I write here to add required attribute in the Name property?
}

解决方案

It is actually possible only through buddy class but it is not recommended way. You should keep your validation in custom view model because often you need different validations for different views but your entity can keep only single set of validation attributes.

Example of buddy class:

using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(EmployeeMetadata))]
public partial class Employee
{
  private class EmployeeMetadata
  {
     [Required]
     public object Name; // Type doesn't matter, it is just a marker
  }
}

这篇关于在设置部分类属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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