EFCore6.0 添加和删除关系表数据(类似级联删除、添加、修改);

数据库里没有设置级联删除,EF Core 6.0版本代码实现添加和删除关系表(类似级联删除、级联添加、级联修改) ,

1、删除关系表,要直接使用上下文操作。

        public async Task DeleteList(ReqestDeleteListModel<int> info)
        {
            using (var trans = wmsDataContext.Database.BeginTransaction())
            {
                try
                {
                    var UserList = await this.repository.Query()
                        .Include(d => d.TUserUserroleRels)
                        .Include(d => d.TWarehouseUserRels)
                        .Where(d => info.ids.Contains(d.UserId)).ToListAsync();
                    if (UserList.Count > 0)
                    {
                        foreach (var item in UserList)
                        {
                            if (item.TUserUserroleRels.Count > 0)
                            {
                                //失败案例
                                //item.TUserUserroleRels = null;
                                //await this.unitOfWork.CommitAsync();
                                //var rels = item.TUserUserroleRels.ToList();
                                //foreach (var a in rels)
                                //{
                                //    item.TUserUserroleRels.Remove(a);
                                //    await this.unitOfWork.CommitAsync();
                                //}
                                //正确案例
                                var rels = item.TUserUserroleRels;
                                wmsDataContext.TUserUserroleRels.RemoveRange(rels.ToArray());
                                await this.unitOfWork.CommitAsync();

                            }
                            if (item.TWarehouseUserRels.Count > 0)
                            {
                                var rels = item.TWarehouseUserRels;
                                wmsDataContext.TWarehouseUserRels.RemoveRange(rels.ToArray());
                                await this.unitOfWork.CommitAsync();

                            }

                            this.repository.Delete(item);
                            await this.unitOfWork.CommitAsync();
                        }

                    }
                    await trans.CommitAsync();
                }
                catch (Exception ex)
                {
                    await trans.RollbackAsync();
                    throw ex;
                }
            }

        }

 

2添加关系表(见 Add)

修改关系表(见update,先全部删除再添加,实际还应该加事务)

using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wms.Infrastructure;
using wms.Model.Dtos;
using wms.Model.Entities;
using wms.Repository;

namespace wms.Service
{

    public class UserService : IUserService
    {

        private readonly IUserRepository repository;
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;
        private readonly IEncryption en;
        private readonly IUserUserroleRelRepository userUserroleRelRepository;
        private readonly WmsDataContext wmsDataContext;

        public UserService(IUserRepository repository, IUnitOfWork unitOfWork, IMapper mapper, IEncryption en, WmsDataContext wmsDataContext, IUserUserroleRelRepository userUserroleRelRepository)
        {
            this.repository = repository;
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
            this.en = en;
            this.wmsDataContext= wmsDataContext;
            this.userUserroleRelRepository = userUserroleRelRepository;
        }


        public async Task<UserBaseDto?> Add(UserDto info, string languageId)
        {
            var mstandardId = wmsDataContext.TCompanies.Where(d => d.CompanyId == info.CompanyId).Select(d => d.MstandardId).SingleOrDefault();
            info.MstandardId = mstandardId;
            var dbInfo = this.mapper.Map<TUser>(info);
            ((UserRepository)this.repository).Insert(dbInfo);
            await this.unitOfWork.CommitAsync();
           
            if (info.UserRoleId.Length > 0)
            {
                var userRoleId = info.UserRoleId.ToList();
                var userRoles = this.wmsDataContext.TUserRoles.AsQueryable().Where(d => userRoleId.Contains(d.UserRoleId)).ToList();
                foreach (var a in userRoles)
                {
                    dbInfo.TUserUserroleRels.Add(new TUserUserroleRel {UserRoleId=a.UserRoleId });
                }
            }
         
            if (info.WarehouseId.Length > 0)
            {
                var warehouseId = info.WarehouseId.ToList();
                var warehouseList = this.wmsDataContext.TWarehouses.AsQueryable().Where(d => warehouseId.Contains(d.WarehouseId)).ToList();
                foreach (var a in warehouseList)
                {
                   dbInfo.TWarehouseUserRels.Add(new TWarehouseUserRel { WarehouseId = a.WarehouseId });
                }
            }
            this.wmsDataContext.SaveChanges();

            return await GetInfo(dbInfo.UserId,languageId);
        }

        //public async Task Delete(int id)
        //{
        //    var user = await this.repository.Query().Where(d => d.UserId == id).SingleOrDefaultAsync();
        //    if (user != null)
        //    {
        //        this.repository.Delete(user);
        //        await this.unitOfWork.CommitAsync();
        //    }
        //}

        //public async Task DeleteList(ReqestDeleteListModel<int> info)
        //{
        //    var UserList = await this.repository.Query().Where(d => info.ids.Contains(d.UserId)).ToListAsync();
        //    if (UserList.Count > 0)
        //    {
        //        foreach (var item in UserList)
        //        {
        //            this.repository.Delete(item);
        //        }
        //        await this.unitOfWork.CommitAsync();
        //    }
        //}

        public async Task DeleteList(ReqestDeleteListModel<int> info)
        {
            using (var trans = wmsDataContext.Database.BeginTransaction())
            {
                try
                {
                    var UserList = await this.repository.Query()
                        .Include(d => d.TUserUserroleRels)
                        .Include(d => d.TWarehouseUserRels)
                        .Where(d => info.ids.Contains(d.UserId)).ToListAsync();
                    if (UserList.Count > 0)
                    {
                        foreach (var item in UserList)
                        {
                            if (item.TUserUserroleRels.Count > 0)
                            {
                                //失败案例
                                //item.TUserUserroleRels = null;
                                //await this.unitOfWork.CommitAsync();
                                //var rels = item.TUserUserroleRels.ToList();
                                //foreach (var a in rels)
                                //{
                                //    item.TUserUserroleRels.Remove(a);
                                //    await this.unitOfWork.CommitAsync();
                                //}
                                //正确案例
                                var rels = item.TUserUserroleRels;
                                wmsDataContext.TUserUserroleRels.RemoveRange(rels.ToArray());
                                await this.unitOfWork.CommitAsync();

                            }
                            if (item.TWarehouseUserRels.Count > 0)
                            {
                                var rels = item.TWarehouseUserRels;
                                wmsDataContext.TWarehouseUserRels.RemoveRange(rels.ToArray());
                                await this.unitOfWork.CommitAsync();

                            }

                            this.repository.Delete(item);
                            await this.unitOfWork.CommitAsync();
                        }

                    }
                    await trans.CommitAsync();
                }
                catch (Exception ex)
                {
                    await trans.RollbackAsync();
                    throw ex;
                }
            }

        }
        public async Task<UserBaseDto?> GetInfo(int userid)
        {
            var info = await this.repository.Query().Include(d=>d.TUserUserroleRels).ThenInclude(d=>d.UserRole).Include(d => d.Company).Where(d => d.UserId == userid).SingleOrDefaultAsync();
            return this.mapper.Map<UserBaseDto?>(info);
        }

        public async Task<UserBaseDto?> GetInfo(int userid, string languageId)
        {
           return await GetQueryable(languageId).Where(d => d.UserId == userid).SingleOrDefaultAsync();
        }

        public async Task<UserBaseDto?> GetInfo(string username, string languageId)
        {
            var info = await this.repository.Query().Include(d => d.Company).Where(d => d.UserName == username).SingleOrDefaultAsync();

            return this.mapper.Map<UserBaseDto?>(info);
        }

        public async Task<List<UserNameDto>> GetOperatorList(int companyId)
        {
            var list = await this.repository.Query().Where(d=>d.TUserUserroleRels.Select(d=>d.UserRoleId).Contains(2)).Where(d=>d.CompanyId==companyId).ToListAsync();

            return this.mapper.Map<List<UserNameDto>>(list);
        }
        public IQueryable<UserBaseDto> GetQueryable(string languageId)
        {
            //var query = this.repository.Query();
            //var d = this.wmsDataContext.TDictionaries.Include(d => d.TDictTrans);
            var query = from w in this.wmsDataContext.TUsers.Include(d=>d.TWarehouseUserRels).Include(d => d.Company) //this.repository.Query()
                        join t in this.wmsDataContext.TCompanies
                        on w.CompanyId equals t.CompanyId
                        //join ur in this.wmsDataContext.TWarehouseUserRels
                        //on w.UserId equals ur.UserId
                        //join d6 in d.Where(d => d.TypeId == 6)
                        //on w.UserType equals d6.Dkey
                        //join d7 in d.Where(d => d.TypeId == 7)
                        //on w.UserStatus equals d7.Dkey
                        select new UserBaseDto
                        {
                            UserId = w.UserId,
                            UserName = w.UserName,
                            UserType = w.UserType,
                            UserStatus = w.UserStatus,
                            FirstName = w.FirstName,
                            LastName = w.LastName,
                            Email = w.Email,
                            CellPhone = w.CellPhone,
                            TelPhone = w.TelPhone,
                            PreferredLanguageId = w.PreferredLanguageId,
                            CompanyId = w.CompanyId,
                            Name = w.FirstName + " " + w.LastName,
                            CompanyName = t.CompanyName,
                            //UserTypeName = d6.TDictTrans.Where(d => d.LanguageId == languageId).Single().Dvalue,
                            //UserStatusName = d7.TDictTrans.Where(d => d.LanguageId == languageId).Single().Dvalue,
                            UserRoleName = String.Join("|", w.TUserUserroleRels.Select(d => d.UserRole.UserRoleName).ToArray()),
                            UserRoleId = w.TUserUserroleRels.Select(d => d.UserRoleId).ToArray(), 
                            WarehouseId = w.TWarehouseUserRels.Select(d => d.WarehouseId).ToArray(),
                            // Company = this.mapper.Map<CompanyDto>(w.Company),
                            MstandardId = w.MstandardId,
                            //WarehouseName = String.Join("|", w.TWarehouseUserRels.Select(d => d.Warehouse.Name).ToArray()),
                        };

            //return query.ProjectTo<UserBaseDto>(mapper.ConfigurationProvider);
            return query;
        }

        public async Task<UserBaseDto?> Update(UserDto info,string languageId)
        {
            //异步返回序列的唯一元素,如果序列为空,则返回默认值;如果序列中有多个元素,此方法将引发异常。
            var m = await repository.Query().Include(d=>d.TUserUserroleRels).Include(d=>d.TWarehouseUserRels).Where(d => d.UserId == info.UserId).SingleOrDefaultAsync();//.ThenInclude(d => d.UserRole)
            if (m == null)
            {
                return null!;
            }
            if (info.Password != null && info.Password.Length > 0)
            {
                m.Password = en.GetMD5(info.Password);
            }
            m.UserType = info.UserType;
            m.UserStatus = info.UserStatus;
            m.UserType = info.UserType;
            m.LastName = info.LastName;
            m.FirstName = info.FirstName;
            m.Email = info.Email;
            m.CellPhone = info.CellPhone;
            m.TelPhone = info.TelPhone;
            m.PreferredLanguageId = info.PreferredLanguageId;
            m.CompanyId = info.CompanyId;
            //m.TUserUserroleRels.Clear();
            //repository.Update(m);
            //await this.unitOfWork.CommitAsync();
            foreach (var item in m.TUserUserroleRels)
            {
                this.wmsDataContext.TUserUserroleRels.Remove(item);
            }
            foreach (var item in m.TWarehouseUserRels)
            {
                this.wmsDataContext.TWarehouseUserRels.Remove(item);
            }
            this.wmsDataContext.SaveChanges();
            if (info.UserRoleId.Length > 0)
            {
                var userRoleId = info.UserRoleId.ToList();
                var userRoles = this.wmsDataContext.TUserRoles.AsQueryable().Where(d => userRoleId.Contains(d.UserRoleId)).ToList();
                foreach (var a in userRoles)
                {
                    this.wmsDataContext.TUserUserroleRels.Add(new TUserUserroleRel { UserRoleId = a.UserRoleId,UserId= m.UserId });
                }
            }
            if (info.WarehouseId.Length > 0)
            {
                var warehouseId = info.WarehouseId.ToList();
                var warehouseList = this.wmsDataContext.TWarehouses.AsQueryable().Where(d => warehouseId.Contains(d.WarehouseId)).ToList();
                foreach (var a in warehouseList)
                {
                    this.wmsDataContext.TWarehouseUserRels.Add(new TWarehouseUserRel { WarehouseId = a.WarehouseId, UserId = m.UserId });
                }
            }

            repository.Update(m);
            await this.unitOfWork.CommitAsync();
            return await GetInfo(info.UserId, languageId);
        }


    }
}

 

posted @ 2023-03-21 17:09  hao_1234_1234  阅读(415)  评论(0编辑  收藏  举报