一对一关系导致异常:AssociationSet处于“已删除”状态。给定多重性约束 [英] 1-to-1 relationship causing exception: AssociationSet is in the 'Deleted' state. Given multiplicity constraints

查看:243
本文介绍了一对一关系导致异常:AssociationSet处于“已删除”状态。给定多重性约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先按照此处规定的方法使用EF代码建立了一对一关系:

I have set up a 1-to-1 relationship using EF code first following the method prescribed here:

实体框架中的单向一对一关系

我的映射看起来像这样...

My mapping looks like this ...

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Asset>()
        .HasRequired(i => i.NewsItem)
        .WithOptional(e => e.Asset)
        .Map(m => m.MapKey("NewsItemId"));
}

但是当我遇到此异常时...

But when I get this exception ...


Asset_NewsItem'AssociationSet中的关系处于已删除状态。给定多重性约束,相应的 Asset_NewsItem_Source也必须处于已删除状态。

A relationship from the 'Asset_NewsItem' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Asset_NewsItem_Source' must also in the 'Deleted' state.

只要此代码运行:

var entry = _db.NewsItems.Find(id);

entry.Asset = new Asset();

_db.DbContext.SaveChanges();

如果我明确标记了要删除的与NewsItem相关的先前资产,但可以使事情正常进行似乎有点古怪。看起来,根据映射,上面的代码应该可以正常工作...用新的资产替换旧的资产。

I can get things to work if I explicitly mark the previous Asset associated to the NewsItem for deletion, BUT it just seems kinda wonky. It seems like, based on the mapping, the above code should simply work ... replacing the old Asset with the new one.

我做错了吗?我需要在映射中指定一些可以使事情正常进行的东西吗?还是必须先删除然后再添加相关对象这样的EF方法?

Am I doing something wrong? Is there something I need to specify in the mapping that will get things working right? Or, is it simply the EF way to have to delete and then add associated objects like this?

推荐答案

EF是这样工作的。您已经加载了具有相关资产的条目,现在要分配新资产。此操作将使您的旧资产与任何条目都不相关,但是映射不允许这样做(您指定 Asset 资产必须具有相关的 Entry )。因此,在分配新资产以满足映射约束之前,您必须删除旧资产或将其分配给另一个条目。

It is how EF works. You have loaded an entry with related asset and now you want to assign a new asset. This operation will make your old asset unrelated to any entry but it is not allowed by your mapping (you specified that Asset must have related Entry). So you must delete the old asset or assign it to another entry prior to assigning the new asset to satisfy your mapping constraints.

这篇关于一对一关系导致异常:AssociationSet处于“已删除”状态。给定多重性约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆