Valeriy Y.
Valeriy Y.

Reputation: 43

How can I remove relationship between entities in EF6 code-first?

I have one-to-many relationship between objects A and B.

public class A
{
    public int Id { get; set; }
    public int? OwnerId { get; set; }
    public B Owner { get; set; }
}

public class B
{
    public int Id { get; set; }
    public ObservableCollection<A> OwnedObjects { get; set; }
}

i have

AutoDetectChangesEnabled = false;
ProxyCreationEnabled = false;

I want to delete A from OwnedObjects but not from database.

this:

var b = Bs.Find(id);
Entry(b).Collection(_=>_.OwnedObjects).Load();
var someObjToRemove = b.OwnedObjects[0];
b.OwnedObjects.Remove(someObjToRemove);
Entry(b).State = EntityState.Modified;
SaveChanges();

doesn't help

this:

var b = Bs.Find(id);
Entry(b).Collection(_=>_.OwnedObjects).Load();
var someObjToRemove = b.OwnedObjects[0];
someObjToRemove.OwnerId = null;
Entry(someObjToRemove).State = EntityState.Modified;
SaveChanges();

throws exception:

A referential integrity constraint violation occurred: The property value(s) of 'B.Id' on one end of a relationship do not match the property value(s) of 'A.OwnerId' on the other end.

I can't delete object A and create another one without Owner because there is many other objects related with A

It's seems to be not so hard to do. But I can't find any solution

Upvotes: 0

Views: 157

Answers (1)

Valeriy Y.
Valeriy Y.

Reputation: 43

Ok. Only solution i found it's to call ChangeTracker.DetectChanges(); after adding or removing items.

var itemToAdd = As.Find(a1.Id);
b.OwnedObjects.Add(itemToAdd);

var itemToRemove = As.Find(a2.Id);
b.OwnedObjects.Remove(itemToRemove);

ChangeTracker.DetectChanges();
SaveChanges();

works great. but ChangeTracker.Entries() contains only instances of A modified. And if I replace ChangeTracker.DetectChanges() by

Entry(itemToAdd).State = EntityState.Modified; 
Entry(itemToRemove).State = EntityState.Modified;

it doesn't work again.

So i think, calling ChangeTracker.DetectChanges(); it is most simplest way to solve this problem

Upvotes: 1

Related Questions