.NetCore中EFCore的使用整理(三)-关联表操作
一、查询关联表数据
StudyAboard_TestContext _context = new StudyAboard_TestContext(); CrmRole role = _context.CrmRole .Include(q => q.CrmRoleMenu) .Where(q => q.Id == 1).FirstOrDefault();
二、清空关联表数据
StudyAboard_TestContext _context = new StudyAboard_TestContext(); CrmRole role = _context.CrmRole .Include(q => q.CrmRoleMenu) .Where(q => q.Id == 1).FirstOrDefault(); //清空关联表数据 _context.CrmRoleMenu.RemoveRange(role.CrmRoleMenu); _context.SaveChanges();
三、添加关联表数据
1.完全添加
CrmRole role = new CrmRole() { Name = "测试角色" }; role.CrmRoleMenu.Add(new CrmRoleMenu() { MenuId = 1 }); role.CrmRoleMenu.Add(new CrmRoleMenu() { MenuId = 2 }); _context.CrmRole.Add(role); _context.SaveChanges();
2.读取后添加
StudyAboard_TestContext _context = new StudyAboard_TestContext(); CrmRole role = _context.CrmRole .Include(q => q.CrmRoleMenu) .Where(q => q.Id == 1).FirstOrDefault(); //添加关联表数据 role.CrmRoleMenu.Add(new CrmRoleMenu() { MenuId = 1 }); role.CrmRoleMenu.Add(new CrmRoleMenu() { MenuId = 2 }); _context.SaveChanges();
更多: