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

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

问题描述

我有一个由实体框架(EF)生成的员工课程。

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;}
    }
}

现在我想在name属性中放置一个必需的属性,以便在另一个由我写的员工部分类中使用MVC3验证为了扩展由EF生成的一个,所以如果我刷新EF生成的模型,我不必重写我的代码。

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.

伙伴类示例:

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