反射当前程序集
public static void InitialPermission() { //ArrayList a = new ArrayList(); //a.Add(new { name= 1,age = 2 }); //a[0].GetType().GetProperty("name").GetValue(a[0]); List<Type> controllerTypes = new List<Type>(); //Dictionary<string, string> permission = new Dictionary<string, string>(); List<Tuple<string, string>> tuple = new List<Tuple<string, string>>(); foreach (Assembly assembly in BuildManager.GetReferencedAssemblies()) { controllerTypes.AddRange(assembly.GetTypes().Where(type => typeof(IController).IsAssignableFrom(type))); } controllerTypes.ForEach(t => { if (!t.FullName.Contains("System")) { var methods = t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).ToList(); methods.ForEach(m => { //if (!permission.Keys.Contains(m.Name)) //{ // permission.Add(m.Name, t.Name); //} if (!tuple.Contains(new Tuple<string, string>(m.Name, t.Name))) { tuple.Add(new Tuple<string, string>(m.Name, t.Name)); } }); } }); //if (permission != null) //{ // PermissionService ps = new PermissionService(); // ps.InitialPermission(permission); //} if (tuple.Count > 0) { PermissionService ps = new PermissionService(); ps.InitialPermission(tuple); } }
使用元组数据
public void InitialPermission(List<Tuple<string, string>> tuple) { //检查数据库permission EntityContext db = new EntityContext(); Role adminRole = db.Roles.Where(a => a.RoleName == "admin").FirstOrDefault(); if (adminRole != null) { foreach (var per in tuple) { if (db.Permissions.Include("Role").Where(p => p.ActionName == per.Item1 && p.ControllerName == per.Item2).Count() <= 0) { db.Permissions.Add(new Permission() { ActionName = per.Item1, ControllerName = per.Item2 }); } } } db.SaveChanges(); //检查role_permission var list = db.Permissions.ToList(); list.ForEach(a => { if (db.Role_Permissions.Where(b => b.Permission.PerId == a.PerId && b.Role.RoleId == adminRole.RoleId).Count() <= 0) { //Permission p = db.Permissions.FirstOrDefault(b => b.PerId == a.PerId); //Role r = db.Roles.FirstOrDefault(b => b.RoleId == adminRole.RoleId); db.Role_Permissions.Add(new Role_Permission() { PerId = a.PerId, RoleId = adminRole.RoleId }); } }); db.SaveChanges(); }