Entity Framework多对多关系
1.模型类
/// <summary> /// 角色类 /// </summary> [Table("RoleTB")] public class RoleTB { [Key] public int ID{get;set;} public string Name { get; set; } public string Desc { get; set; } public int Status { get; set; } [NotMapped] public virtual List<MenuTB> MenuTBs { get; set; } [NotMapped] public virtual List<UserTB> UserTBs { get; set; } }
/// <summary> /// 用户 /// </summary> [Table("UserTB")] public class UserTB { [Key] public int ID { get; set; } public string UserName { get; set; } public string Password { get; set; } public string HeadImage { get; set; } [NotMapped] public virtual List<RoleTB> RoleTBs { get; set; } }
/// <summary> /// 角色和用户中间表 /// </summary> [Table("RoleUserTR")] public class RoleUserTR { [Key] [Column(Order = 0)] [ForeignKey("RoleTB")] public int RoleID { get; set; } public virtual RoleTB RoleTB { get; set; } [Key] [Column(Order = 1)] [ForeignKey("UserTB")] public int UserID { get; set; } public virtual UserTB UserTB { get; set; } }
2.测试代码
using(var dbContext=new EntityDbContext()) { RoleTB role = new RoleTB { Name="总管理员" }; UserTB user1 = new UserTB { UserName = "admin", Password = "123456" }; UserTB user2 = new UserTB { UserName = "liandy", Password = "123456" }; dbContext.RoleTBs.Add(role); dbContext.UserTBs.Add(user1); dbContext.UserTBs.Add(user2); dbContext.SaveChanges(); RoleUserTR roleUserTR1 = new RoleUserTR { RoleID = role.ID, UserID=user1.ID }; RoleUserTR roleUserTR2 = new RoleUserTR { RoleID = role.ID, UserID = user2.ID }; dbContext.RoleUserTRs.Add(roleUserTR1); dbContext.RoleUserTRs.Add(roleUserTR2); dbContext.SaveChanges(); }
using (var dbContext = new EntityDbContext()) { UserTB user = dbContext.UserTBs.Where(u => u.UserName == "liandy").FirstOrDefault(); dbContext.UserTBs.Remove(user); dbContext.SaveChanges(); }
using (var dbContext = new EntityDbContext()) { RoleTB role = dbContext.RoleTBs.Where(u => u.ID == 1).FirstOrDefault(); List<UserTB> userTBs = dbContext.RoleUserTRs.Where(u => u.RoleID == role.ID).Select(u => u.UserTB).ToList(); }
3.验证数据库
/// <summary> /// 角色类 /// </summary> [Table("RoleTB")] public class RoleTB { [Key] public int ID{get;set;} public string Name { get; set; } public string Desc { get; set; } public int Status { get; set; } [NotMapped] public virtual List<MenuTB> MenuTBs { get; set; } [NotMapped] public virtual List<UserTB> UserTBs { get; set; } }