Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 381
wgpubs Avatar asked Jul 17 '12 04:07

wgpubs


1 Answers

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.

like image 104
Ladislav Mrnka Avatar answered Sep 21 '22 19:09

Ladislav Mrnka