简体   繁体   English

使用Fluent API配置ASP MVC 4的实体框架级联删除

[英]Entity Framework Cascade Delete using Fluent API Configuration asp mvc 4

I have two class called User and Event. 我有两个类,分别称为User和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 : 事件类与User具有一对多关系,如下所示:

[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 : 我的modelBuilder配置如下所示:

 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. 示例:如果删除用户,则要删除该用户组织的所有事件,并在其ID出现的每一行的用户和朋友之间的中间表“ frienship”中删除其userID。

My delete method which catch Exception : 我的捕获异常的delete方法:

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'. 当用户组织了一个事件时,异常为: “ DELETE语句与REFERENCE约束\\” FK_dbo.Event_dbo.User_OrganizerId \\“发生冲突。冲突发生在数据库\\” Database \\“,表\\” dbo.Event \\“的列中'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'. **当我们要删除的用户具有特权时:**“ DELETE语句与REFERENCE约束\\” FK_dbo.Friendship_dbo.User_FriendId \\“发生冲突。冲突发生在数据库\\”数据库\\“,表\\” dbo.Friendship \\ ”,列“ FriendId”。

How I am supposed to modify my Api fluent configuration ? 我应该如何修改Api流利的配置?

You cannot delete user which PK is referenced with foreign key in other table. 您不能删除其他表中用外键引用了PK的用户。

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). 在“用户”表中添加新列(在您的情况下为类的新属性)“ isDeleted”,其类型为“位”(在您的情况下为布尔型)。 '0' for false and '1' for true. “ 0”代表假,“ 1”代表真。

I hope was helpful. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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