Setting attributes of a property in partial classes

前端 未结 3 1491
鱼传尺愫
鱼传尺愫 2020-12-16 11:01

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

public partial class employee
{
    private string name;
    public string Name
    {
        ge         


        
3条回答
  •  余生分开走
    2020-12-16 11:42

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

提交回复
热议问题