Search code examples
c#asp.net-mvcpoco

Is it a good practice to add methods to the POCOs or to create separate class to update the values of the POCOs?


Is it a good practice to add methods to the POCOs or to create separate class to update the values of the POCOs in case we need that?

For example,

public class ForUser
{
    [Required]
    public int Depratment { get; set; }

    public List<SelectListItem> DepartmentsList { get; set; }

    [Required]
    public int Role { get; set; }

    [Required]
    [StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The First Name Should  Be More Than Three Letters")]
    public string FirstName { get; set; }

    [StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The Mid Name Should  Be More Than Three Letters")]
    public string MidName { get; set; }

    [Required]
    [StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The Last Name Should  Be More Than Three Letters")]
    public string LastName { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    [StringLength(14, MinimumLength = 10 , ErrorMessage = "Length Of The Mid Name Should  Be More Than Nine Letters and Less than fourteen Letters")]
    [RegularExpression(@"^[+]?[0-9]*", ErrorMessage="Phone Number is not correct")]
    public string PhoneNumber { get; set; }

    [Required]
    public string Password { get; set; }


    public int UserId { get; set; }
    public int Company { get; set; }
    public int Country { get; set; }
    public List<SelectListItem> Roles { get; set; }
}

I use it just to hold the data to update the model entity or to return data to the view. Sometimes I need to update some properties before I send the object to the view, like the list called Roles in the above example, so I am wondering about if I should add the methods to the POCO class or is it better to create a class to update the properties?


Solution

  • Here is an answer to this question:

    A POCO is not a DTO. POCO stands for Plain Old CLR Object, or Plain Old C# Object. It’s basically the .Net version of a POJO, Plain Old Java Object. A POCO is your Business Object. It has data, validation, and any other business logic that you want to put in there. But there’s one thing a POCO does not have, and that’s what makes it a POCO. POCOs do not have persistence methods. If you have a POCO of type Person, you can’t have a Person.GetPersonById() method, or a Person.Save() method. POCOs contain only data and domain logic, no persistence logic of any kind. The term you’ll hear for this concept is Persistence Ignorance (PI). POCOs are Persistence Ignorant.

    I prefer to read the whole article, not just to get the answer to your question, but also understand the difference between the POCO and DTO.