I have 2 classes containg POCO entities in MVC3
public class TeamMember
{
public DateTime JoinDate { get; set; }
[Required]
Public string Name{ get; set; }
}
public class Project
{
[Required]
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
I want to set the default value of TeamMember JoinDate
with Project StartDate
.
Can anybody pull me out of this
You could do it in the controller, something like:
if(teamMember.JoinDate == null)
{
teamMember.JoinDate = project.StartDate;
}
and you could add more logic if project.StartDate == null
then project.StartDate = DateTime.Now
.
I'm not sure you can do this as a default in the model itself though.
Update
As you have it, I don't think the Project StartDate
can see the TeamMember JoinDate
, I think you will need to give them a one to one relationship. I'm not sure of the exact syntax since I'm not on my work system, but something like this should work:
public class TeamMember
{
public DateTime JoinDate
{
get { return this.JoinDate; }
set { JoinDate = this.Project.StartDate; }
}
[Required]
public string Name{ get; set; }
public virtual Project Project { get; set; }
}
public class Project
{
[Required]
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
Update 2
Thinking about it, you need to allow JoinDate to be null or else it will throw a validation error, then you need to check to see if there is a value for it. Something more like this:
public class TeamMember
{
public DateTime? JoinDate
{
get { return this.JoinDate; }
set
{
if(JoinDate == null)
{
JoinDate = this.Project.StartDate;
}
else
{
JoinDate = JoinDate;
}
}
}
[Required]
public string Name{ get; set; }
public virtual Project Project { get; set; }
}