上篇介绍了一对多关系,下面介绍下多对多关系代码编写。
1、新建model实体,User是用户类,Role是角色类,由于是多对多关系,必须得有一个中间类,所以产生了UserRole类
1 public class User 2 { 3 public int Id { get; set; } 4 public string Name { get; set; } 5 6 public virtual ICollection<UserRole> UserRoles { set; get; } 7 } 8 9 public class Role 10 { 11 public int Id { get; set; } 12 public string Name { get; set; } 13 14 public virtual ICollection<UserRole> UserRoles { set; get; } 15 } 16 17 public class UserRole 18 { 19 public int Id { get; set; } 20 public int UId { get; set; } 21 public int RId { get; set; } 22 23 public virtual User User { set; get; } 24 public virtual Role Role { set; get; } 25 }
2、创建一个EntityContext并继承自DbContext
1 public class EntityContext : DbContext 2 { 3 public EntityContext() 4 : base("name=DBConnectionString") 5 { 6 7 } 8 9 public DbSet<User> User { get; set; } 10 public DbSet<Role> Role { get; set; } 11 public DbSet<UserRole> UserRole { get; set; } 12 13 protected override void OnModelCreating(DbModelBuilder modelBuilder) 14 { 15 modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); 16 base.OnModelCreating(modelBuilder); 17 } 18 }
3、在web.config文件中添加数据库连接字符串
1 <connectionStrings> 2 <add name="DBConnectionString" connectionString="Data Source=.;Initial Catalog=ManyToMany;Integrated Security=true" providerName="System.Data.SqlClient" /> 3 </connectionStrings>
4、接着创建实体映射
1 public class UserMap : EntityTypeConfiguration<User> 2 { 3 public UserMap() 4 { 5 ToTable("User"); 6 HasKey(u => u.Id); 7 } 8 } 9 10 public class RoleMap : EntityTypeConfiguration<Role> 11 { 12 public RoleMap() 13 { 14 ToTable("Role"); 15 HasKey(r => r.Id); 16 } 17 } 18 19 public class UserRoleMap : EntityTypeConfiguration<UserRole> 20 { 21 public UserRoleMap() 22 { 23 ToTable("UserRole"); 24 HasKey(ur => ur.Id); 25 26 //WillCascadeOnDelete:不使用级联删除 27 HasRequired(pt => pt.User).WithMany(p => p.UserRoles).HasForeignKey(pt => pt.UId).WillCascadeOnDelete(false); 28 29 HasRequired(pt => pt.Role).WithMany(t => t.UserRoles).HasForeignKey(pt => pt.RId).WillCascadeOnDelete(false); 30 } 31 }
5、我们写一些操作,让Code First生成数据库并验证数据是否新增
1 var user = new User() { Name = "Bob" }; 2 db.Set<User>().Add(user); 3 4 var role = new Role() { Name = "admin" }; 5 db.Set<Role>().Add(role); 6 7 db.SaveChanges(); 8 9 var ur = new UserRole() { RId = role.Id, UId = user.Id }; 10 db.Set<UserRole>().Add(ur); 11 db.SaveChanges(); 12 13 //var list = db.Set<User>().Include("UserRoles").ToList(); 14 //如果需要查出UserRoles下的Role可以这样 15 //避免通过延迟加载需要访问数据库(同样的外键实体只会访问一次,但是比较多的话还是用以下方式) 16 var list = db.Set<User>().Include("UserRoles.Role").ToList();
6、数据库关系图