EF代码优先使用

一、使用

1、脑海中建立三个表,用户、权限、角色

分别:T_Users(用户表)、T_Roles(角色表)、T_Permissions(权限表)、T_UserRoles(用户一对多角色)、T_RolePermissions(角色一对多权限)

 sql语句地址:https://www.cnblogs.com/520bug/articles/11050690.html

2、建立三个类库,分别命名为:XXX.Service、XXX.DTO、XXX.IService。

3、在XXX.Service类库下建立三个文件夹:分别命名:Entities、ModelConfig、Service

4、在XXX.Service类库下建立一个类,命名:XXXDbContext.cs

XXXContext.cs代码如下:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using XXX.Service.Entities;

namespace XXX.Service
{
     public class XXXDbContext:DbContext
    {
        //name=connStr 表示使用链接字符串中字为connStr的去链接数据库
        public ZSZDbContext() : base("name=connStr")
        {
            //Database.SetInitializer<ZSZDbContext>(null);
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
        }

        #region 设置实体集
        public DbSet<UserEntity> AdminUsers { get; set; }
        public DbSet<PermissionEntity> Permissions { get; set; }
        public DbSet<RoleEntity> Roles { get; set; }
        #endregion
    }
}

5、在XXX.Service类库下的Entities文件夹下建立四个类,分别命名:BaseEntity.cs、UserEntity.cs、PermissionEntity.cs、RoleEntity.cs

BaseEntity.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.Service.Entities
{
    //父类,要求所有的实体类继承它
    public abstract class BaseEntity
    {
        /// <summary>
        /// 编号 主键
        /// </summary>
        public long Id { get; set; }
        /// <summary>
        /// 创建日期
        /// </summary>
        public DateTime CreateDateTime { get; set; } = DateTime.Now;
        /// <summary>
        /// 是否软删除
        /// </summary>
        public bool IsDeleted { get; set; } = false;
    }
}

UserEntity.cs代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.Service.Entities
{
    /// <summary>
    /// 用户
    /// </summary>
    public class UserEntity:BaseEntity
    {
        /// <summary>
        /// 用户名字
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 手机号
        /// </summary>
        public string PhoneNum { get; set; }
        /// <summary>
        /// 邮件
        /// </summary>
        public string Email { get; set; }
        /// <summary>
        /// 密码盐
        /// </summary>
        public string PasswordSalt { get; set; }
         /// <summary>
        /// 密码哈希
        /// </summary>
        public string PasswordHash { get; set; }
        /// <summary>
        /// 登录错误的次数
        /// </summary>
        public int LoginErrorCount { get; set; }
        /// <summary>
        /// 最后登录的时间
        /// </summary>
        public DateTime? LastLoginErrorDateTime { get; set; }
        /// <summary>
        /// 用户有哪些角色,多对多关系
        /// </summary>
        public virtual ICollection<RoleEntity> Roles { get; set; } = new List<RoleEntity>();
    }
}

PermissionEntity.cs代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.Service.Entities
{
    /// <summary>
    /// 权限 一个权限属于多个角色,一个角色有多个权限
    /// </summary>
    public class PermissionEntity :BaseEntity
    {
        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// 权限名称
        /// </summary>
        public string Name { get; set; }

        public virtual ICollection<RoleEntity> Roles { get; set; } = new List<RoleEntity>();
    }
}

RoleEntity.cs代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.Service.Entities
{
    public class RoleEntity :BaseEntity
    {
        /// <summary>
        /// 角色名称
        /// </summary>
        public string Name { get; set; }


        //既可以一张表对应一个Entity,关系表也建立实体,也可以像这样直接让对象带属性,隐式的关系表
        public virtual ICollection<PermissionEntity> Permissions { get; set; } = new List<PermissionEntity>();

        public ICollection<UserEntity> Users { get; set; } = new List<UserEntity>();
    }
}

6、 在XXX.Service类库下的ModelConfig文件夹下建立三个类,分别命名:UserConfig.cs、PermissionConfig.cs、RoleConfig.cs

UserConfig.cs代码如下:using System;

using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.Service.Entities;

namespace XXX.Service.ModelConfig
{
    class UserConfig : EntityTypeConfiguration<UserEntity>
    {
        public UserConfig()
        {
            ToTable("T_Users");
HasMany(u => u.Roles).WithMany(r => r.Users).Map(m=>m.ToTable("T_UserRoles") .MapLeftKey("UserId").MapRightKey("RoleId")); Property(e => e.Name).HasMaxLength(50).IsRequired(); Property(e => e.Email).HasMaxLength(30).IsRequired().IsUnicode(false);//varchar(30) Property(e => e.PhoneNum).HasMaxLength(20).IsRequired().IsUnicode(false); Property(e => e.PasswordSalt).HasMaxLength(20).IsRequired().IsUnicode(false); Property(e => e.PasswordHash).HasMaxLength(100).IsRequired().IsUnicode(false); } } }

PermissionConfig.cs代码如下:

using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.Service.Entities;

namespace XXX.Service.ModelConfig
{
    class PermissionConfig : EntityTypeConfiguration<PermissionEntity>
    {
        public PermissionConfig()
        {
            ToTable("T_Permissions");
            Property(p => p.Description).IsOptional().HasMaxLength(1024);
            Property(p => p.Name).IsRequired().HasMaxLength(50);
        }
    }
}

RoleConfig.cs代码如下:

using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.Service.Entities;

namespace XXX.Service.ModelConfig
{
    class RoleConfig: EntityTypeConfiguration<RoleEntity>
    {
        public RoleConfig()
        {
            ToTable("T_Roles");
            HasMany(r => r.Permissions).WithMany(p => p.Roles).Map(m=>m.ToTable("T_RolePermissions")
                .MapLeftKey("RoleId").MapRightKey("PermissionId"));
            Property(p => p.Name).IsRequired().HasMaxLength(50);
        }
    }
}

7、在XXX.DTO类库下建立四个类,分别命名:BaseDTO.cs、UserDTO.cs、PermissionDTO.cs、RoleDTO.cs

BaseDTO.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.DTO
{
    public abstract class BaseDTO
    {
        public long Id { get; set; }
        public DateTime CreateDateTime { get; set; }
    }

}

UserDTO.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.DTO
{
    public class AdminUserDTO : BaseDTO
    {
        public String Name { get; set; }
        public String PhoneNum { get; set; }
        public String Email { get; set; }public int LoginErrorCount { get; set; }
        public DateTime? LastLoginErrorDateTime { get; set; }
    }

}

PermissionDTO.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.DTO
{
    public class PermissionDTO : BaseDTO
    {
        public String Name { get; set; }
        public String Description { get; set; }
    }

}

RoleDTO.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.DTO
{
    public class RoleDTO : BaseDTO
    {
        public String Name { get; set; }
    }

}

8、在XXX.IService类库下建立四个接口类,分别命名:IServiceSupport.cs、IUserService.cs、IPermissionService.cs、IRoleService.cs

IServiceSupport.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.IService
{
    public interface IServiceSupport
    {
    }
}

IUserService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.DTO;

namespace XXX.IService
{
    public interface IUserService:IServiceSupport
    {
        //加入一个用户,name用户姓名,phoneNum手机号,password密码,email,cityId城市id(null表示总部)
        long AddUser(String name, String phoneNum, String password, String email);

        void UpdateUser(long id, string name, string phoneNum, String password, string email);

        //获取所有管理员
        UserDTO[] GetAll();

        //根据id获取DTO
        UserDTO GetById(long id);

        //根据手机号获取DTO
        UserDTO GetByPhoneNum(String phoneNum);

        //检查用户名密码是否正确
        bool CheckLogin(String phoneNum, String password);

        //软删除
        void MarkDeleted(long adminUserId);

        //判断UserId这个用户是否有permissionName这个权限项(举个例子)
        //HasPermission(3,"User.Add")
        bool HasPermission(long UserId, String permissionName);

        void RecordLoginError(long id);//记录错误登录一次
        void ResetLoginError(long id);//重置登录错误信息
    }

}

IPermissionService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.DTO;

namespace XXX.IService
{
    public interface IPermissionService:IServiceSupport
    {
        long AddPermission(string permName, string description);
        //根据id修改描述
        void UpdatePermission(long id,string permName, string description);

        void MarkDeleted(long id);
        PermissionDTO GetById(long id);
        PermissionDTO[] GetAll();
        PermissionDTO GetByName(String name);//GetByName("User.Add")

        //获取角色的权限
        PermissionDTO[] GetByRoleId(long roleId);

        //给角色roleId增加权限项id permIds
        void AddPermIds(long roleId, long[] permIds);

        //更新角色role的权限项:先删除再添加
        void UpdatePermIds(long roleId, long[] permIds);
    }

}

IRoleService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.DTO;

namespace XXX.IService
{
    public interface IRoleService:IServiceSupport
    {
        //新增角色
        long AddNew(String roleName);
        void Update(long roleId, String roleName);
        void MarkDeleted(long roleId);
        RoleDTO GetById(long id);
        RoleDTO GetByName(string name);
        RoleDTO[] GetAll();
        //给用户userId增加权限roleIds
        void AddRoleIds(long userId, long[] roleIds);

        //更新权限,先删再加
        void UpdateRoleIds(long userId, long[] roleIds);

        //获取用户的角色
        RoleDTO[] GetByUserId(long userId);
    }

}

9、 在XXX.Service类库下的Service文件夹下建立三个类,分别命名:BaseService.cs、UserService.cs、PermissionService.cs、RoleService.cs

BaseService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XXX.IService;
using XXX.Service.Entities;

namespace XXX.Service
{
    //这个类叫CommonService
    class BaseService<T> where T:BaseEntity
    {
        private XXXDbContext ctx;
        public BaseService(XXXDbContext ctx)
        {
            this.ctx = ctx;
        }

        /// <summary>
        /// 获取所有没有软删除的数据
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return ctx.Set<T>().Where(e=>e.IsDeleted==false);
        }

        /// <summary>
        /// 获取总数据条数
        /// </summary>
        /// <returns></returns>
        public long GetTotalCount()
        {
            return GetAll().LongCount();
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public IQueryable<T> GetPagedData(int startIndex,int count)
        {
            return GetAll().OrderBy(e => e.CreateDateTime)
                .Skip(startIndex).Take(count);
        }

        /// <summary>
        /// 查找id=id的数据,如果找不到返回null
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetById(long id)
        {
            return GetAll().Where(e=>e.Id==id).SingleOrDefault();
        }

        public void MarkDeleted(long id)
        {
            var data = GetById(id);
            data.IsDeleted = true;
            ctx.SaveChanges();
        }
    }
}

UserService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Service.Entities;
using System.Data.Entity;
using ZSZ.CommonProject;

namespace ZSZ.Service
{
    public class AdminUserService : IAdminUserService
    {
        public long AddAdminUser(string name, string phoneNum, 
            string password, string email, long? cityId)
        {
            AdminUserEntity user = new AdminUserEntity();
            user.CityId = cityId;
            user.Email = email;
            user.Name = name;
            user.PhoneNum = phoneNum;
            string salt = CommonHelper.CreateVerifyCode(5);//
            user.PasswordSalt = salt;
            //Md5(盐+用户密码)
            string pwdHash = CommonHelper.CalcMD5(salt+password);
            user.PasswordHash = pwdHash;
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs 
                    = new BaseService<AdminUserEntity>(ctx);
                bool exists = bs.GetAll().Any(u => u.PhoneNum == phoneNum);
                if(exists)
                {
                    throw new ArgumentException("手机号已经存在"+phoneNum);
                }
                ctx.AdminUsers.Add(user);
                ctx.SaveChanges();
                return user.Id;
            }
        }

        public bool CheckLogin(string phoneNum, string password)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs = new BaseService<AdminUserEntity>(ctx);
                //除了错不可怕,最怕的是有错但是表面“风平浪静”
                var user = bs.GetAll().SingleOrDefault(u=>u.PhoneNum==phoneNum);
                if (user == null)
                {
                    return false;
                }
                string dbHash = user.PasswordHash;
                string userHash = CommonHelper.CalcMD5(user.PasswordSalt+password);
                //比较数据库中的PasswordHash是否和MD5(salt+用户输入密码)一直
                return userHash == dbHash;
            }
        }

        private AdminUserDTO ToDTO(AdminUserEntity user)
        {
            AdminUserDTO dto = new AdminUserDTO();
            dto.CityId = user.CityId;
            if(user.City!=null)
            {
                dto.CityName = user.City.Name;//需要Include提升性能
                //如鹏总部(北京)、如鹏网上海分公司、如鹏广州分公司、如鹏北京分公司
            }
            else
            {
                dto.CityName = "总部";
            }
            
            dto.CreateDateTime = user.CreateDateTime;
            dto.Email = user.Email;
            dto.Id = user.Id;
            dto.LastLoginErrorDateTime = user.LastLoginErrorDateTime;
            dto.LoginErrorTimes = user.LoginErrorTimes;
            dto.Name = user.Name;
            dto.PhoneNum = user.PhoneNum;
            return dto;
        }

        public AdminUserDTO[] GetAll()
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                //using System.Data.Entity;才能在IQueryable中用Include、AsNoTracking
                //AsNoTracking 如果取出来的数据只是显示不会修改保存数据库
                BaseService<AdminUserEntity> bs 
                    = new BaseService<AdminUserEntity>(ctx);
                return bs.GetAll().Include(u=>u.City)
                    .AsNoTracking().ToList().Select(u => ToDTO(u)).ToArray();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cityId">如果为null则获取总部的管理员;否则是获取某个地区的</param>
        /// <returns></returns>
        public AdminUserDTO[] GetAll(long? cityId)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs
                    = new BaseService<AdminUserEntity>(ctx);
                //CityId is null;CityId=3
                var all = bs.GetAll().Include(u => u.City)
                    .AsNoTracking().Where(u => u.CityId == cityId);
                return all.ToList().Select(u => ToDTO(u)).ToArray();
            }
        }

        public AdminUserDTO GetById(long id)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs
                    = new BaseService<AdminUserEntity>(ctx);
                //这里不能用bs.GetById(id);因为无法Include、AsNoTracking()等
                var user = bs.GetAll().Include(u => u.City)
                    .AsNoTracking().SingleOrDefault(u=>u.Id==id);
                    //.AsNoTracking().Where(u=>u.Id==id).SingleOrDefault();
                //var user = bs.GetById(id); 用include就不能用GetById
                if (user==null)
                {
                    return null;
                }
                return ToDTO(user);
            }
        }

        public AdminUserDTO GetByPhoneNum(string phoneNum)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs
                    = new BaseService<AdminUserEntity>(ctx);
                var users = bs.GetAll().Include(u => u.City)
                    .AsNoTracking().Where(u => u.PhoneNum == phoneNum);
                int count = users.Count();
                if(count <= 0)
                {
                    return null;
                }
                else if(count==1)
                {
                    return ToDTO(users.Single());
                }
                else
                {
                    throw new ApplicationException("找到多个手机号为"+phoneNum+"的管理员");
                }
            }
        }

        //HasPermission(5,"User.Add")
        public bool HasPermission(long adminUserId, string permissionName)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs
                    = new BaseService<AdminUserEntity>(ctx);
                var user = bs.GetAll().Include(u => u.Roles)
                    .AsNoTracking().SingleOrDefault(u=>u.Id==adminUserId);
                //var user = bs.GetById(adminUserId);
                if (user==null)
                {
                    throw new ArgumentException("找不到id="+adminUserId+"的用户");
                }
                //每个Role都有一个Permissions属性
                //Roles.SelectMany(r => r.Permissions)就是遍历Roles的每一个Role
                //然后把每个Role的Permissions放到一个集合中
                //IEnumerable<PermissionEntity>
                return user.Roles.SelectMany(r => r.Permissions)
                    .Any(p=>p.Name==permissionName);
            }
        }

        public void MarkDeleted(long adminUserId)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs 
                    = new BaseService<AdminUserEntity>(ctx);
                bs.MarkDeleted(adminUserId);
            }
        }

        public void RecordLoginError(long id)
        {
            throw new NotImplementedException();
        }

        public void ResetLoginError(long id)
        {
            throw new NotImplementedException();
        }

        public void UpdateAdminUser(long id, string name, string phoneNum, 
            string password, string email, long? cityId)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs
                    = new BaseService<AdminUserEntity>(ctx);
                var user = bs.GetById(id);
                if(user==null)
                {
                    throw new ArgumentException("找不到id="+id+"的管理员");
                }
                user.Name = name;
                user.PhoneNum = phoneNum;
                user.Email = email;
                user.PasswordHash = 
                    CommonHelper.CalcMD5(user.PasswordSalt+password);
                user.CityId = cityId;                
                ctx.SaveChanges();
            }
        }
    }
}

PermissionService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Service.Entities;

namespace ZSZ.Service
{
    public class PermissionService : IPermissionService
    {
        public long AddPermission(string permName,string description)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<PermissionEntity> permBS = new BaseService<PermissionEntity>(ctx);
                bool exists = permBS.GetAll().Any(p=>p.Name==permName);
                if(exists)
                {
                    throw new ArgumentException("权限项已经存在");
                }
                PermissionEntity perm = new PermissionEntity();
                perm.Description = description;
                perm.Name = permName;
                ctx.Permissions.Add(perm);
                ctx.SaveChanges();
                return perm.Id;
            }
        }

        public void UpdatePermission(long id,string permName,string description)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<PermissionEntity> bs = new BaseService<PermissionEntity>(ctx);
                var perm = bs.GetById(id);
                if(perm == null)
                {
                    throw new ArgumentException("id不存在" + id);
                }
                perm.Name = permName;
                perm.Description = description;
                ctx.SaveChanges();
            }
        }
        public void MarkDeleted(long id)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<PermissionEntity> bs = new BaseService<PermissionEntity>(ctx);
                bs.MarkDeleted(id);
            }
        }

        public void AddPermIds(long roleId, long[] permIds)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> roleBS 
                    = new BaseService<RoleEntity>(ctx);
                var role = roleBS.GetById(roleId);
                if(role==null)
                {
                    throw new ArgumentException("roleId不存在"+roleId);
                }
                BaseService<PermissionEntity> permBS
                    = new BaseService<PermissionEntity>(ctx);
                var perms = permBS.GetAll()
                    .Where(p => permIds.Contains(p.Id)).ToArray();
                foreach(var perm in perms)
                {
                    role.Permissions.Add(perm);
                }
                ctx.SaveChanges();
            }
        }

        private PermissionDTO ToDTO(PermissionEntity p)
        {
            PermissionDTO dto = new PermissionDTO();
            dto.CreateDateTime = p.CreateDateTime;
            dto.Description = p.Description;
            dto.Id = p.Id;
            dto.Name = p.Name;
            return dto;
        }

        public PermissionDTO[] GetAll()
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<PermissionEntity> bs = new BaseService<PermissionEntity>(ctx);
                return bs.GetAll().ToList().Select(p=>ToDTO(p)).ToArray();
            }
        }

        public PermissionDTO GetById(long id)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<PermissionEntity> bs = new BaseService<PermissionEntity>(ctx);
                var pe = bs.GetById(id);
                return pe == null ? null : ToDTO(pe);
            }
        }

        public PermissionDTO GetByName(string name)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<PermissionEntity> bs = new BaseService<PermissionEntity>(ctx);
                var pe = bs.GetAll().SingleOrDefault(p=>p.Name==name);
                return pe == null ? null : ToDTO(pe);
            }
        }

        public PermissionDTO[] GetByRoleId(long roleId)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> bs = new BaseService<RoleEntity>(ctx);
                return bs.GetById(roleId).Permissions.ToList().Select(p => ToDTO(p)).ToArray();
            }
        }

        //2,3,4
        //3,4,5
        public void UpdatePermIds(long roleId, long[] permIds)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> roleBS
                    = new BaseService<RoleEntity>(ctx);
                var role = roleBS.GetById(roleId);
                if (role == null)
                {
                    throw new ArgumentException("roleId不存在" + roleId);
                }
                role.Permissions.Clear();
                BaseService<PermissionEntity> permBS
                    = new BaseService<PermissionEntity>(ctx);
                var perms = permBS.GetAll()
                    .Where(p => permIds.Contains(p.Id)).ToList();
                foreach (var perm in perms)
                {
                    role.Permissions.Add(perm);
                }
                ctx.SaveChanges();
            }
        }
    }
}

RoleService.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Service.Entities;

namespace ZSZ.Service
{
    public class RoleService : IRoleService
    {
        public long AddNew(string roleName)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> roleBS 
                    = new BaseService<RoleEntity>(ctx);
                bool exists = roleBS.GetAll().Any(r => r.Name == roleName);
                //正常情况不应该执行这个异常,因为UI层应该把这些情况处理好
                //这里只是“把好最后一关”
                if (exists)
                {
                    throw new ArgumentException("角色名字已经存在"+roleName);
                }
                RoleEntity role = new RoleEntity();
                role.Name = roleName;
                ctx.Roles.Add(role);
                ctx.SaveChanges();
                return role.Id;
            }
        }

        public void AddRoleIds(long adminUserId, long[] roleIds)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> userBS 
                    = new BaseService<AdminUserEntity>(ctx);
                var user = userBS.GetById(adminUserId);
                if(user==null)
                {
                    throw new ArgumentException("用户不存在" + adminUserId);
                }
                BaseService<RoleEntity> roleBS = new BaseService<RoleEntity>(ctx);
                var roles = roleBS.GetAll().Where(r=>roleIds.Contains(r.Id)).ToArray();
                foreach(var role in roles)
                {
                    user.Roles.Add(role);
                }
                ctx.SaveChanges();
            }
        }

        private RoleDTO ToDTO(RoleEntity en)
        {
            RoleDTO dto = new RoleDTO();
            dto.CreateDateTime = en.CreateDateTime;
            dto.Id = en.Id;
            dto.Name = en.Name;
            return dto;
        }

        public RoleDTO[] GetAll()
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> bs = new BaseService<RoleEntity>(ctx);
                return bs.GetAll().ToList().Select(p => ToDTO(p)).ToArray();
            }
        }

        public RoleDTO[] GetByAdminUserId(long adminUserId)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> bs = new BaseService<AdminUserEntity>(ctx);
                var user = bs.GetById(adminUserId);
                if(user==null)
                {
                    throw new ArgumentException("不存在的管理员"+adminUserId);
                }
                return user.Roles.ToList().Select(r=>ToDTO(r)).ToArray();
            }
        }

        public RoleDTO GetById(long id)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> bs = new BaseService<RoleEntity>(ctx);
                var role = bs.GetById(id);
                return role == null ? null : ToDTO(role);
            }
        }

        public RoleDTO GetByName(string name)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> bs = new BaseService<RoleEntity>(ctx);
                var role = bs.GetAll().SingleOrDefault(r => r.Name == name);
                return role == null ? null : ToDTO(role);
            }
        }

        public void MarkDeleted(long roleId)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> bs = new BaseService<RoleEntity>(ctx);
                bs.MarkDeleted(roleId);
            }
        }

        public void Update(long roleId, string roleName)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<RoleEntity> roleBS = new BaseService<RoleEntity>(ctx);
                bool exists = roleBS.GetAll().Any(r=>r.Name==roleName&&r.Id!=roleId);
                //正常情况不应该执行这个异常,因为UI层应该把这些情况处理好
                //这里只是“把好最后一关”
                if (exists)
                {
                    throw new ArgumentException("");
                }
                RoleEntity role = new RoleEntity();
                role.Id = roleId;
                ctx.Entry(role).State = System.Data.Entity.EntityState.Unchanged;
                role.Name = roleName;
                ctx.SaveChanges();
            }
        }

        public void UpdateRoleIds(long adminUserId, long[] roleIds)
        {
            using (ZSZDbContext ctx = new ZSZDbContext())
            {
                BaseService<AdminUserEntity> userBS
                    = new BaseService<AdminUserEntity>(ctx);
                var user = userBS.GetById(adminUserId);
                if (user == null)
                {
                    throw new ArgumentException("用户不存在" + adminUserId);
                }
                user.Roles.Clear();
                BaseService<RoleEntity> roleBS = new BaseService<RoleEntity>(ctx);
                var roles = roleBS.GetAll().Where(r => roleIds.Contains(r.Id)).ToArray();
                foreach (var role in roles)
                {
                    user.Roles.Add(role);
                }
                ctx.SaveChanges();
            }
        }
    }
}

二、个人认为需要介绍地方

1、翻译

 

2、介绍

 

三、详细介绍

posted on 2019-06-19 19:25  520bug  阅读(472)  评论(0)    收藏  举报

导航