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.