简体   繁体   中英

Entity Framework Cascade Delete using Fluent API Configuration asp mvc 4

I have two class called User and Event.

Users can organize Events, and can have friends (User).

User class has a many-to-many relationship with Friends, like below :

[Table("User")]
public class User 
{   
  public User() {
   EventOrganized = new List<Event>();
  }
  public virtual ICollection<User> Friends { get; set; }
  public virtual ICollection<Event> EventOrganized { get; set; }
}

Event class has a one-to-many relationship with User, like below :

[Table("Event")]
public class Event
{
  public int OrganizerId { get; set; }
  [ForeignKey("OrganizerId")]

  public virtual User Organizer { get; set; }
}

My Context has :

public DbSet<User> Users { get; set; }
public DbSet<Event> Events{ get; set; }

And my modelBuilder configuration looks like :

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
  base.OnModelCreating(modelBuilder);
  modelBuilder.Entity<User>().HasMany(u => u.Friends).WithMany().Map(
            u =>
            {
                u.MapLeftKey("UserId");
                u.MapRightKey("FriendId");
                u.ToTable("Friendship");
            });
  modelBuilder.Entity<Event>().HasRequired(e => e.Organizer).WithMany().WillCascadeOnDelete(false);

I'd like to be able to remove a User with cascade delete (his events organized, his frienships).

Example : If I delete an user, I want delete all Events organized by this user, and delete his userID in the intermediate table "frienship" between User and Friends at each row where his id appears.

My delete method which catch Exception :

Try {
List<int> friendsIds = userToRemove.Friends.Select(f => f.UserId).ToList();
    foreach (int friendID in friendsIds)
    {
      User friend = db.Users.Find(friendID);
      friend.Friends.Remove(userToRemove);
    }
 db.Users.Remove(userToRemove);
 SaveChanges();
Catch(Exception) {}

When User has organized an Event, Exception is : "The DELETE statement conflicted with the REFERENCE constraint \\"FK_dbo.Event_dbo.User_OrganizerId\\". The conflict occurred in database \\"Database\\", table \\"dbo.Event\\", column 'OrganizerId'.

**When User we want to delete has frienships : ** "The DELETE statement conflicted with the REFERENCE constraint \\"FK_dbo.Friendship_dbo.User_FriendId\\". The conflict occurred in database \\"Database\\", table \\"dbo.Friendship\\", column 'FriendId'.

How I am supposed to modify my Api fluent configuration ?

You cannot delete user which PK is referenced with foreign key in other table.

In this case you can use other logic for deleting users eg:

Add new column in Users table(in your case new property in class) 'isDeleted' which type is 'bit'(in your case boolean type). '0' for false and '1' for true.

I hope was helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM