Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - Setting attributes of a property in partial classes

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?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...