EF code-first, cannot delete foreign key relationship

I have two models shown here:

public class Application
{
  public string Name { get; set; }
  public virtual ICollection<ApplicationTransaction> ApplicationTransactions { get; set; }
}

and

public class ApplicationTransaction
{
  public long ApplicationId { get; set; }
  public virtual Application Application { get; set; }
}

I tried to remove everything ApplicationTransactionfrom Applicationusing this code:

var app = _repository.Get<Application>(i => i.Id == 1);
app.ApplicationTransactions.Clear();
Context.SaveChanges();

but when the context goes to save the changes, an error occurs:

The operation failed: the relationship cannot be changed because one or more properties of the foreign key are not NULL. When a change is made to a relation, set the property of the foreign key associated with it to zero. If the foreign key does not support null values, it is necessary to define a new relation, the property of the foreign key must be assigned another non-zero value, or an object not associated with it must be deleted.

enter image description here

+4
4

, , Application; , .

foreach (ApplicationTransaction applicationTransaction in app.ApplicationTransactions.ToList())
    context.DeleteObject(applicationTransaction);
0

, Fluent API :

 modelBuilder.Entity<Application>()
            .HasOptional(a => a.ApplicationTransactions)
            .WithOptionalPrincipal(a => a.Application);

NULL

0

" " :

var modifiedAppplicationTransactions = context.ChangeTracker.Entries<ApplicationTransactions>().Where(x => x.State == EntityState.Modified);
foreach (var item in modifiedAppplicationTransactions )
{
    if (item.Entity.ApplicationId == null)
    {
        context.Entry(item.Entity).State = EntityState.Deleted;
    }
}
context.SaveChanges():
0
source

I had the same problem and here is the solution:

Trick: when setting up the relationship between the parent and the child, you must create a “composite” key for the child. Thus, when you tell the parent to delete 1 or all of its children, the corresponding records will actually be deleted from the database.

To configure a composite key using the Fluent API:

modelBuilder.Entity<Child>.HasKey(t => new { t.ParentId, t.ChildId });

Then, to remove the related children:

var parent = _context.Parents.SingleOrDefault(p => p.ParentId == parentId);

var childToRemove = parent.Children.First(); // Change the logic 
parent.Children.Remove(childToRemove);

// or, you can delete all children 
// parent.Children.Clear();

_context.SaveChanges();

Done!

0
source

All Articles