Entity framework EF删除具有卸载导航属性的实体

Entity framework EF删除具有卸载导航属性的实体,entity-framework,domain-driven-design,entity-framework-4.1,navigation-properties,Entity Framework,Domain Driven Design,Entity Framework 4.1,Navigation Properties,我有一个实体授权。每项任务都有一个必需的:与一个人的许多关系(NavigationProperty)。我将DbContext API与(LazyLoadingEnabled、AutoDetectChangesEnabled、ValidateOnSaveEnabled、ProxyCreationEnabled)一起使用 现在我想删除一个委托实体。委托书实体由另一个上下文通过AsNoTracking()加载 message.Result. ObserveOn(On<DataCompos

我有一个实体<代码>授权。每项任务都有一个必需的:与一个人的许多关系(NavigationProperty)。我将DbContext API与(LazyLoadingEnabled、AutoDetectChangesEnabled、ValidateOnSaveEnabled、ProxyCreationEnabled)一起使用

现在我想删除一个委托实体。委托书实体由另一个上下文通过
AsNoTracking()
加载

message.Result.
    ObserveOn(On<DataComposition>.Scheduler).
    Where(r => r).
    Subscribe(_ =>
    {
        using (var unit = UnitOfWork.Begin())
        {
            var mandate = this.SelectedItem.OriginalEntity;

            this.mandateRepository.Attach(mandate);
            // mandate.Person.ToString();

            this.mandateRepository.Delete(mandate);

            unit.Commit();
        }

        this.List.RemoveOnUi(this.SelectedItem);
    });
message.Result。
ObserveOn(在调度程序上)。
其中(r=>r)。
订阅(=>
{
使用(var unit=UnitOfWork.Begin())
{
var委托=this.SelectedItem.OriginalEntity;
本.委托书.附(委托书);
//委托书.Person.ToString();
本.mandateRepository.Delete(委托书);
unit.Commit();
}
this.List.RemoveOnUi(this.SelectedItem);
});
现在,在提交过程中,我遇到了以下异常:
在“CodeFirstContainer.Commissions”中的实体参与了“Commission\u Person”关系。找到0个相关的“任务\人员\目标”。预计会有1个“授权\人员\目标”。


如果我在填充/选择过程中包括Person属性,或者如果我访问属性(懒散加载),则删除操作有效,但我不喜欢仅为删除案例具体化/保留多个实体,并且我不喜欢触发多个
删除
查询到db

事实上,如果您已填充导航属性
委托书.Person
,则以下SQL语句

delete [dbo].[Mandates]
where (([Id] = @0) and ([PersonId] = @1))
。。。发送到数据库时,让我认为导航属性确实必须由具有正确的
PersonId的人员填充才能删除父项

我不知道为什么实体框架不发送带有主键的delete语句

delete [dbo].[Mandates]
where ([Id] = @0)
。。。如我所料

编辑

如果
委托
实体对于
人员
导航属性具有外键属性
PersonId
,则预期的SQL(上面第二个)将发送到数据库。在这种情况下,
Person
导航属性可以是
null
,而FK属性
PersonId
的值并不重要

编辑2

如果您不想引入FK属性,则DB往返成本最低的方法可能是获取人员Id,然后在内存中创建具有该密钥的虚拟人员:

// ...
var personId = context.Mandates
    .Where(m => m.Id == mandate.Id)
    .Select(m => m.Person.Id)
    .Single();

mandate.Person = new Person { Id = personId };

this.mandateRepository.Attach(mandate);
this.mandateRepository.Delete(mandate);
// ...