'How to add a foreign key and navigation property to a composite primary key entity?
I have an entity with composite primary key, and I want to add a additional foreign key and its navigation property to it.
But I always get an error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_TaskRelations_Projects_ProjectId". The conflict occurred in database "Database", table "dbo.Projects", column 'Id'
This occurs after running update-database.
This is my entity:
public class TaskRelation
{
public long PrecedingTaskId { get; set; }
public long FollowingTaskId { get; set; }
public long ProjectId { get; set; }
[ForeignKey("PrecedingTaskId")]
[JsonIgnore]
public MainTask PrecedingTask { get; set; }
[ForeignKey("FollowingTaskId")]
[JsonIgnore]
public MainTask FollowingTask { get; set; }
[ForeignKey("ProjectId")]
[JsonIgnore]
public ProjectBase Project { get; set; }
}
My fluent Api is like below:
modelBuilder.Entity<TaskRelation>().HasKey(c => new { c.PrecedingTaskId, c.FollowingTaskId });
modelBuilder.Entity<TaskRelation>()
.HasOne(ta => ta.FollowingTask)
.WithMany(t => t.TaskAssignments)
.HasForeignKey(ta => ta.FollowingTaskId)
.OnDelete(DeleteBehavior.Restrict);
Would you please give me some advice about this problem? Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
