I have a problem with insert procedure in my application in ASP .NET MVC. I describe my environment and after I will explain my problem.
I have 2 model classes: Projects and Task
PROJECT
[Table("Project")]
public class Project
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProjectID { get; set; }
[Required(ErrorMessage = "Name project required")]
[StringLength(300, MinimumLength = 1)]
[DisplayName("Name of Project")]
public string NameProject { get; set; }
//Other properties...
public Project()
{
Tasks = new HashSet<Task>();
}
public virtual ICollection<Task> Tasks { get; set; }
}
TASK
[Table("Task")]
public class Task
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TaskID { get; set; }
[Required(ErrorMessage = "Task Name required")]
[StringLength(300, MinimumLength = 1)]
public string TaskName { get; set; }
public virtual Project Project { get; set; }
}
And this is TASKMANAGER where I insert code to manage dbContext. This is the createNewTask function.
public void createTask(Task task,int projectID)
{
Project pr = db.Project.Find(projectID);
task.Project = pr;
db.Task.Add(task);
db.SaveChanges();
}
And here is a snapshot from my database:
And the problem is:
When I try insert new task, the system give me an error: * Can not add a null value to the column 'Project_ProjectID' for entity 'Task' *.
But, I don't understand this!! When I debug the application, I can see that in the insert function, the variable 'int projectID' is correct, and the line 'Project pr = db.Project.Find(projectID)' works well, but when it's arrive to 'SaveChanges()'... it's crashed.
Anyone can help me?