1-to-1 relationship causing exception: AssociationSet is in the 'Deleted' state. Given multiplicity constraints

北城余情 提交于 2020-07-18 04:16:39

问题


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

Unidirectional One-To-One relationship in Entity Framework

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 ...

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.

Whenever this code runs:

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

entry.Asset = new Asset();

_db.DbContext.SaveChanges();

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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/11516109/1-to-1-relationship-causing-exception-associationset-is-in-the-deleted-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!