简体   繁体   English

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

[英]EntityFramework error when deleting an entity with one-to-one optional relationship

When I try to delete one entity that is related to another entity by a one-to-one relation with both ends as optional, I have this error: 当我尝试通过一对一的关系删除一个与另一个实体相关的实体时,两端都是可选的,我有这个错误:

A relationship from the 'Jury_Slots' AssociationSet is in the 'Deleted' state. 来自'Jury_Slots'AssociationSet的关系处于'已删除'状态。 Given multiplicity constraints, a corresponding 'Jury_Slots_Target' must also in the 'Deleted' state. 给定多重约束,相应的'Jury_Slots_Target'也必须处于'已删除'状态。

My entities: 我的实体:

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; }
}

This is how I declared my relation: 这就是我宣布我的关系的方式:

modelBuilder.Entity<Jury>()
    .HasMany(j => j.Slots)
    .WithRequired(j => j.Jury);

modelBuilder.Entity<JurySlot>()
    .HasOptional(c => c.ApplicantTest)
    .WithOptionalPrincipal(ec => ec.JurySlot);

What I try to do is (the simplest code to reproduce it): var context = new MyContext(); 我尝试做的是(最简单的代码来重现它):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();

Before the call to Remove(), I tried the things that are commented, but without success... 在调用Remove()之前,我尝试了评论的内容,但没有成功......

Does anybody have an idea? 有人有想法吗?

Can't explain why (I guess one of the little EF mysteries), but deleting from the corresponding DbSet does the trick: 无法解释为什么(我猜其中一个小EF的谜团),但从相应的DbSet中删除可以DbSet问题:

...

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

context.SaveChanges();

executes the following commands: 执行以下命令:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM