删除具有一对一可选关系的实体时出现EntityFramework错误

时间:2017-03-16 16:35:41

标签: c# entity-framework entity-framework-6

当我尝试通过一对一关系删除一个与另一个实体相关的实体时,两端都是可选的,我有这个错误:

  

来自' Jury_Slots'的关系AssociationSet在   '删除'州。给定多重约束,相应的   ' Jury_Slots_Target'还必须在“删除”中删除。状态。

我的实体:

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

在调用Remove()之前,我尝试了评论的内容,但没有成功......

有人有想法吗?

1 个答案:

答案 0 :(得分: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))