6

Hi i got an issue with Entity Framework when i try to delete a row in a "binding" table.

The tables look like this:

[Table("Users")]
public class UserEntity : BaseEntity
{
    [Required]
    [MaxLength(30)]
    public string Username { get; set; }
    [Required]
    [MaxLength(200)]
    public string Password { get; set; }

    [Required]
    [MaxLength(200)]
    public string Name { get; set; }

    [Required]
    [MaxLength(20)]
    public string Cellphone { get; set; }

    public virtual ICollection<UserGroupEntity> UserGroups { get; set; }


[Table("Groups")]
public class GroupEntity : BaseEntity
{
    [Required]
    [MaxLength(20)]
    public string Code { get; set; }

    [Required]
    [MaxLength(200)]
    public string Name { get; set; }
}

And now i have the table that binds these two together:

[Table("UserGroups")]
public class UserGroupEntity : BaseEntity
{
    [Required]
    [ForeignKey("User")]
    public int UserId { get; set; }

    [Required]
    [ForeignKey("Group")]
    public int GroupId { get; set; }

    public virtual UserEntity User { get; set; }
    public virtual GroupEntity Group { get; set; }


}

But when i fetch an UserEntity from the database and for example takes the first UserGroup and tries to remove it like shown below i get an error

            UserEntity user = _dataContext.Users
            .Include(x => x.UserGroups)
            .ThenInclude(x => x.Group)
            .SingleOrDefault(x => x.Id == model.Id && !x.IsDeleted);


            UserGroupEntity userGroupBinding = user.UserGroups.First();
            user.UserGroups.Remove(userGroupBinding);

            _dataContext.SaveChanges();

The error message i get:

The association between entity types 'UserEntity' and 'UserGroupEntity' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.  Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.'

My DbContext OnModelCreating method looks like this:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
    {            
        var cascadeFKs = modelBuilder.Model.GetEntityTypes()
            .SelectMany(t => t.GetForeignKeys())
            .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);

        foreach (var fk in cascadeFKs)
            fk.DeleteBehavior = DeleteBehavior.Restrict;



        base.OnModelCreating(modelBuilder);
    }

Does anyone have an idea how to solve this issue? I have been searching alot but never found a solution for my case.

2

1 Answer 1

12

This is a kind of surprising and counterintuitive behavior as side effect of cascade delete behavior (even though deleting the related entity has nothing in common with cascade delete which by definition is supposed to control what happens when deleting the principal entity). It's even documented in Removing relationships section of EF Core documentation:

You can remove a relationship by setting a reference navigation to null, or removing the related entity from a collection navigation.

Removing a relationship can have side effects on the dependent entity, according to the cascade delete behavior configured in the relationship.

etc.

In general removing dependent entity from collection navigation property of the principal should be treated as disassociation (optional relationship) or deletion (required relationship), but apparently current EF Core implementation also throws exception for required relationship with cascade delete off (and some other scenarios).

The only way to fix that without activating cascade delete (which your OnModelCreating is turning off) is to delete (remove) the related entity directly from the corresponding DbSet or DbContext rather than from collection navigation property. e.g. replace

user.UserGroups.Remove(userGroupBinding);

with either

_dataContext.UserGroups.Remove(userGroupBinding);

or

_dataContext.Set<UserGroup>().Remove(userGroupBinding);

or just

_dataContext.Remove(userGroupBinding);

In both cases, after calling SaveChanges the dependent entity will be deleted in database and removed from the collection navigation property by EF Core navigation property fix-up.

1
  • 1
    In my case Remove method doesn't work, used this workaround: foreach (var entity in entities) { context.Entry(entity).State = EntityState.Deleted; } Jun 14, 2022 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.