2017-03-16 35 views
1

當我試圖通過一對一關係刪除一個與另一個實體相關的實體作爲可選時,我有這個錯誤:使用一對一可選關係刪除實體時發生E​​ntityFramework錯誤

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(); 

之前調用刪除(),我想,被評論的事情,但沒有成功......

沒有任何人有一個想法?

+0

似乎你有一個與Jury_Slot關係的實體Jury_Slots_Target。 – Marcelo

回答

3

不能解釋爲什麼(我猜的小EF的謎團之一),並採用相應的DbSet刪除的伎倆:

... 

//existing.Slots.Remove(lastSlot); 
context.JurySlots.Remove(lastSlot); 

context.SaveChanges(); 

執行以下命令:

UPDATE [dbo].[ApplicantTests] 
SET [JurySlot_Id] = NULL 
WHERE (([Id] = @0) AND ([JurySlot_Id] = @1)) 

DELETE [dbo].[JurySlots] 
WHERE (([Id] = @0) AND ([Jury_Id] = @1)) 
+0

謝謝,它的工作!我不認爲直接從上下文中刪除。 – maftieu

相關問題