當我試圖通過一對一關係刪除一個與另一個實體相關的實體作爲可選時,我有這個錯誤:使用一對一可選關係刪除實體時發生EntityFramework錯誤
A relationship from the 'Jury_Slots' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Jury_Slots_Target' must also in the 'Deleted' state.
我的實體:
public class ApplicantTest
{
[Key]
public int Id { get; set; }
// some other properties
public virtual JurySlot JurySlot { get; set; }
}
public class JurySlot
{
[Key]
public int Id { get; set; }
// some other properties
public virtual Jury Jury { get; set; }
public virtual ApplicantTest ApplicantTest { get; set; }
}
public class Jury
{
[Key]
public int Id { get; set; }
public virtual ICollection<JurySlot> Slots { get; set; }
}
這是我宣佈我的關係:
modelBuilder.Entity<Jury>()
.HasMany(j => j.Slots)
.WithRequired(j => j.Jury);
modelBuilder.Entity<JurySlot>()
.HasOptional(c => c.ApplicantTest)
.WithOptionalPrincipal(ec => ec.JurySlot);
我試圖做的是(最簡單的代碼來重現它): var context = new MyContext();
var existing = context.Jurys.Include(j => j.Slots.Select(c => c.ApplicantTest)).Single(j => j.Id == 5);
var lastSlot = existing.Slots.First(c => c.ApplicantTest != null);
// does not work #1
//lastSlot.ApplicantTest = null;
// does not work #2
//context.Entry(lastSlot.ApplicantTest).State = EntityState.Modified;
//lastSlot.ApplicantTest.JurySlot = null;
//lastSlot.ApplicantTest = null;
existing.Slots.Remove(lastSlot);
// exception thrown...
context.SaveChanges();
之前調用刪除(),我想,被評論的事情,但沒有成功......
沒有任何人有一個想法?
似乎你有一個與Jury_Slot關係的實體Jury_Slots_Target。 – Marcelo