M Kenyon II
M Kenyon II

Reputation: 4264

I'm missing something with this entity framework relationship

We're using code first for our project. I have two tables, that when saving I get this error message:

"Unable to determine the principal end of the 'PublicationSystem.Model.TaskAssignment_Task' relationship. Multiple added entities may have the same primary key."

Here are the models:

[Table("TaskItem")]
public class TaskItem
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TaskId { get; set; }

    //...

    public ICollection<TaskAssignment> Assignees { get; set; }
}

[Table("TaskAssignment")]
public class TaskAssignment : BaseEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TaskAssignmentId { get; set; }

    public int TaskId { get; set; }

    [ForeignKey("TaskId")]
    public TaskItem Task { get; set; }

    //...

}

What am I missing?

Upvotes: 0

Views: 32

Answers (1)

E-Bat
E-Bat

Reputation: 4892

As you are using Identity strategy for primary keys, each new TaskItem will have TaskId = 0, so you can't relay on this value because EF will not be able resolve relationships when you are saving more than one of them. What you can do is to build the relation through object reference:

var newTask = new TaskItem {...} 
var newTaskAssignment = new TaskAssignment { Task = newTask }

If you really need the PKs for TaskItem you will need to call SaveChange first before you can use it.

Upvotes: 1

Related Questions