1

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:

Database Snapshot

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?

4

1 回答 1

0

您需要将以下属性添加到您的任务实体: - public virtual int ProjectId。

最后,我建议添加这样的实体:- Project.Task.Add(yourCurrentTask)。

于 2013-05-16T09:30:41.030 回答