實體框架插入我使用實體框架6,我不斷收到以下錯誤:現有的導航屬性的實體
Violation of PRIMARY KEY constraint 'PK_AssignmentType'. Cannot insert duplicate key in object 'dbo.AssignmentType'.
正如你看到我試圖將實體AssignmentType
的狀態更改爲unchanged
。當我將實體Assignment
指定爲AssignmentType
的外鍵,然後將導航屬性AssignmentType
設置爲null時,我仍然得到相同的錯誤(在foreach循環中Assignments
,而不是在Comments
foreach循環中)。
實體框架在哪裏跟蹤實體AssignmentType
?爲什麼它仍然認爲它是一個新的實體而不是現有的實體?
實體Reporting
和Assignment
之間存在多對多關係。
[Route("")]
[HttpPost]
public IHttpActionResult Add(ReportingDTO data)
{
Reporting reporting = new Reporting { ID = Guid.NewGuid(), Date = DateTime.Now };
foreach (Assignment assignment in data.Assignments)
{
_db.Entry(assignment.AssignmentType).State = EntityState.Unchanged;
if (assignment.Reporting.Count > 0)
{
_db.Entry(assignment).State = EntityState.Added;
_db.Entry(assignment).State = EntityState.Modified;
}
reporting.Assignment.Add(assignment);
}
foreach (Comment comment in data.Comments)
{
comment.ID = Guid.NewGuid();
comment.AssignmentID = comment.Assignment.ID;
comment.Assignment = null;
comment.ReportingID= reporting.ID;
}
using(var transaction = _db.Database.BeginTransaction())
{
_db.Reporting.Add(reporting);
_db.Comments.AddRange(data.Comments);
_db.SaveChanges();
transaction.Commit();
}
return Ok(reporting);
}
Reporting.cs
[Table("Reporting")]
public partial class Reporting
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Reporting()
{
Assignment= new HashSet<Assignment>();
}
[Key]
public Guid ID{ get; set; }
[Column(TypeName = "date")]
public DateTime Date{ get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Assignment> Assignment{ get; set; }
}
Assignment.cs
[Table("Assignment")]
public partial class Assignment
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Assignment()
{
Reporting = new HashSet<Reporting>();
}
[Key]
public Guid OID { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
public Guid AssignmentTypeID { get; set; }
[Required]
[StringLength(100)]
public string Project { get; set; }
public bool Completed { get; set; }
[ForeignKey("AssignmentTypeID")]
public virtual AssignmentType AssignmentType { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Reporting> Reporting { get; set; }
}
AssignmentType
[Table("AssignmentType")]
public partial class AssignmentType
{
[Key]
public Guid ID { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
}
你有一個外鍵:Assignment.AssignmentTypeId? – Atlasmaybe
是的,我願意。在ReportingDTO中,這個字段等於null。 – adiii4
你可以發佈你的數據模型嗎? – Atlasmaybe