0

I am getting the following error when I remove an entity from a collection and then persist it back. I understand that I need to setup my relationships to delete the entity when the relationship is removed, but I am unable to figure out exactly what needs to be done despite searching via Google and SO.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable.

I have three tables: Role, Permission, and RolePermission. I am trying to remove a RolePermission from a Role.

public RoleMap()
{
    HasKey(t => t.Id);
    ToTable("Role");
    Property(t => t.RoleName).HasColumnName("RoleName");

    HasMany(t => t.RolePermissions).WithRequired(t => t.Role).HasForeignKey(t => t.RoleId);
}

public PermissionMap()
{
    HasKey(t => t.Id);
    ToTable("Permission");
    Property(t => t.ApplicationId).HasColumnName("ApplicationId");
    Property(t => t.PermissionName).HasColumnName("PermissionName");
    Property(t => t.IsActive).HasColumnName("IsActive");

    HasRequired(t => t.Application).WithMany(t => t.Permissions).HasForeignKey(t => t.ApplicationId);
}

public RolePermissionMap()
{
    HasKey(t => t.Id);
    ToTable("RolePermission");
    Property(t => t.PermissionId).HasColumnName("PermissionId");
    Property(t => t.RoleId).HasColumnName("RoleId");

    HasRequired(t => t.Permission).WithMany(t => t.RolePermissions).HasForeignKey(t => t.PermissionId);
    HasRequired(t => t.Role).WithMany(t => t.RolePermissions).HasForeignKey(t => t.RoleId);
}

The code to remove looks like this (everything is attached to the DBContext):

foreach (RolePermission rolePermission in permissionsToRemove)
{
   role.RolePermissions.Remove(rolePermission);
}

//call commit/saveChanges here

What do I need to setup in order for Remove to actually cause a delete?

1 Answer 1

0

I think you don't need the RolePermission entity at all, unless you're storing more information in addition to the foreign key fields. So, try to building a many-to-many relationship between Role and Permission. Let me show you an example with my own code:

            modelBuilder.Entity<User>()
            .HasMany(u => u.Roles)
            .WithMany(r => r.Users)
            .Map(x => {
                x.ToTable("USER_ROLE_XREF", dbsch);
                x.MapLeftKey("ID_USER");
                x.MapRightKey("ID_ROLE");
            });

Your Answer

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

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