Search code examples
c#classobjectannotationsrequired

C# - DataAnnnotations with objects


I have a question about DataAnnotations. I have the following two classes;

public class Project
{

   public int ID { get; set; }

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

   [Required]
   public User Manager { get; set; }

}

public class User
{

   public int ID { get; set; }

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

At the moment my idea is not working. What I want is, when I make a Project you need to put a User with only an ID (you don't need the name, because it will search for it on the database) and a projectname. And if I want to make an User it only needs a name. What is the best way to make this work? I don't want to change User to int because when I do a GET on Project I want the User as a object returned.

Thanks for the help!


Solution

  • I would add the int and keep the object:

    public class Project
    {
    
        public int ID { get; set; }
    
        [Required]
        public string ProjectName { get; set; }
    
        [Required]
        public int ManagerID { get; set; }
    
        public User Manager { get; set; }
    }
    

    In data entry the user must enter/select the ID but the object is retrieved when the data is fetched and updated when the ID is changed.