简体   繁体   English

使用PK删除表行以及其他表中有外键的行

[英]Delete table row using PK and row in other table where it's a foreign key

I have a method that deletes a user from my Users table by userId: 我有一个方法可以通过userId从我的用户表中删除用户:

public void DeleteUser(int id)
    {
        User delObj = (Users.Where(u => u.UserId == id)).Single();
        Users.Remove(delObj);
        SaveChanges();
    }

The primary key userId is also used as a foreign key in a userroles table where there is a UserRoleId (PK), UserId (FK), and RoleId (FK). 主键userId还在有UserRoleId(PK),UserId(FK)和RoleId(FK)的userroles表中用作外键。 I am unsure how to knock out both rows in both tables with one method. 我不确定如何用一种方法删除两个表中的两行。

Thanks in advance! 提前致谢!

Here are the exact properties: 这里是确切的属性:

public class User
{
    [Key]
    public int UserId { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<UserRole> UserRoles { get; set; }
}



public class UserRole
    {
        [Key]
        public int UserRoleId { get; set; }
        public int UserId { get; set; }
        public short RoleId { get; set; }

        public virtual Role Role { get; set; }
    }

Implement the relation between your entities in c#. 在c#中实现实体之间的关系。 For example make the collection of Roles entities on User object. 例如,对用户对象进行角色实体的收集。 The ORM (I guess you are using EntityFramework or NHibernate) will take care of removing dependant objects automatically. ORM(我想您正在使用EntityFramework或NHibernate)将负责自动删除依赖对象。

class User {
     public virtual ICollection<UserRole> UserRoles { get; set; }
}

It should be mapped as many to many relation. 应该将其映射为多对多关系。

And on your DBContext you must add: 并且在您的DBContext上,您必须添加:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany(u => u.UserRoles)
            .WithOptional().WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);
    }

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

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