Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF code-first, cannot delete foreign key relation

I have a 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 delete all ApplicationTransaction of Application with this code:

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

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

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

enter image description here

like image 940
Behrooz Avatar asked Nov 11 '22 15:11

Behrooz


1 Answers

I had the exact same problem and here's the solution:

Trick: When setting up the relationship between Parent and Child, you'll HAVE TO create a "composite" key on the child. This way, when you tell the Parent to delete 1 or all of its children, the related records will actually be deleted from the database.

To configure composite key using Fluent API:

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

Then, to delete 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!

like image 74
Mosh Avatar answered Nov 14 '22 22:11

Mosh