出现的问题是映射表RoleMenus中只存在 ParentID 为Null的值
如下代码生成的数据库中 RoleMenus 只存在2条数据
Role_RoleID Menu_MenuID
1 1
1 2
缺少一条 "子菜单表一" 的映射数据
1 class Program
2 {
3 static void Main(string[] args)
4 {
5
6 Database.SetInitializer<Entity>(new DropCreateDatabaseAlways<Entity>());
7
8 var menus = new List<Menu> { new Menu { Title = "菜单一", Chlidren = new List<Menu> { new Menu { Title = "子菜单一" } } }, new Menu { Title = "菜单二" } };
9
10 var roles = new Role { RoleName = "管理员", Menus = menus };
11
12 using (var context = new Entity())
13 {
14 context.Role.Add(roles);
15 context.SaveChanges();
16 }
17 }
18 }
19
20 public class Menu
21 {
22 public int MenuId { get; set; }
23 public string Title { get; set; }
24
25 public int? ParentId { get; set; }
26
27 [ForeignKey("ParentId")]
28 public virtual List<Menu> Chlidren { get; set; }
29
30 public virtual List<Role> Role { get; set; }
31 }
32
33 public class Role
34 {
35 public int RoleId { get; set; }
36 public string RoleName { get; set; }
37
38 public virtual List<Menu> Menus { get; set; }
39 }
40
41 public class Entity : DbContext
42 {
43 public Entity() : base("Data Source=.;Initial Catalog=EntityDemo;Integrated Security=True;Pooling=False") { }
44
45 public DbSet<Menu> Menu { get; set; }
46
47 public DbSet<Role> Role { get; set; }
48
49 }