.NET5中的EF Core数据层仓储模式

使用EF框架:
Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

程序集框架.NET5

目录

    • DbContext数据上下文配置
    • 数据层接口
    • 数据层接口实现
    • 数据层具体示例
    • 业务层调用:
    • 数据层接口,实现
    • 控制器调用:
    • Program.cs
    • Startup.cs

DbContext数据上下文配置

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore.Diagnostics;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong.DAL_Impl
{
    /// 
    /// EF数据上下文
    /// 
    /// 
    /// 创建时间:2021-7-29 10:02:152
    /// 作者:王浩力
    /// 
    public class MyDbContext : DbContext
    {
        //public MyDbContext()
        //{
        //    //设置执行超时限制
        //    //this.Database.SetCommandTimeout(60);
        //}

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //连接字符串配置
            //#connctionDb   server=.;Database=gdd_tu_shi_fen_gong;uid=sa;pwd=123456
            string connectionString = MyConfigReader.GetConfigValue("connctionDb");

#if WPF_Debug || WPF_Release

            //如果是WPF端,连接字符串是加密的,这里需要解密
            connectionString = FenGong.Model.Tool.AesHelpter.AESDecryptByHex(connectionString);

#endif

            optionsBuilder.UseSqlServer(connectionString);


            //设置不跟踪所有查询  
            optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

            //启用敏感数据日志记录
            optionsBuilder.EnableSensitiveDataLogging();

#if DEBUG
            //记录日志          
            optionsBuilder.LogTo(msg =>
            {
                //调试-窗口消息
                System.Diagnostics.Debug.WriteLine(msg);
                //输出-窗口消息
                Console.WriteLine(msg);
            });
#endif

        }

        public virtual DbSet<Animation> Animation { get; set; }
        public virtual DbSet<Animation_step> Animation_step { get; set; }
        public virtual DbSet<Ground_lead> Ground_lead { get; set; }
        public virtual DbSet<Map_mark> Map_mark { get; set; }
   
        

    }
}


PageModel

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

namespace WebMvcNetCore.TuShi.FenGong.Model
{

    /// 
    /// 分页数据
    /// 
    /// 
    public class PageModel<T>
    {
        /// 
        /// 当前页码
        /// 
        public int PageIndex { get; set; }

        /// 
        /// 页大小
        /// 
        public int PageSize { get; set; }

        /// 
        /// 总记录数
        /// 
        public int Total { get; set; }

        /// 
        /// 当前页数据列表
        /// 
        public List<T> List { get; set; }

        public PageModel()
        {

        }

        public PageModel(List<T> items, int total, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            Total = total;
            List = items;
        }
    }
}

SaveModel

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

namespace WebMvcNetCore.TuShi.FenGong.Model
{
    /// 
    /// 批量(修改或新增)记录
    /// 
    /// 操作的数据库表实体
    public class SaveModel
    {
        /// 
        /// 实体类型;删除时不传;
        /// 
        public Type ModelType { get; set; }

        /// 
        /// 要修改或新增的实体,删除时要传
        /// 
        public object Model { get; set; }

        /// 
        /// 要修改的列名称,参考"id","Name","DataType";
        /// 如果是新增记录,则此字段传null,此时Model的IsUpdate设置为false;
        /// 删除时不传;
        /// 
        public string[] Columns { get; set; }

        /// 
        /// 删除此条记录吗? true删除,false不删除,默认false
        /// 
        public bool IsDelete { get; set; } = false;

    }
}

Result

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

namespace WebMvcNetCore.TuShi.FenGong.Model
{
    /// 
    /// 返回消息, Code默认200表示操作成功,500表示异常
    /// 
    /// 2019-10-8 10:40:13 王浩力 添加
    public struct Result
    {
        /// 
        /// 操作代码,默认200表示操作成功,500表示异常
        /// 
        public int Code;

        /// 
        /// 消息
        /// 
        public string Msg;

        /// 
        /// 返回数据
        /// 
        public object Data;

        /// 
        /// code=200,表示成功
        /// 
        /// 
        public Result(object data)
        {
            Code = 200;
            Data = data;
            Msg = "操作成功";
        }

        /// 
        /// code=200,表示操作成功
        /// 
        /// 
        public Result(bool success)
        {
            Code = 200;
            Msg = "操作成功";
            Data = null;
        }

        public Result(string msg, int code = 500)
        {
            Code = code;
            Msg = msg;
            Data = null;
        }

        public Result(object data, int code = 200)
        {
            Code = code;
            Data = data;
            Msg = "操作成功";
        }

        public Result(object data, string msg = "", int code = 200)
        {
            Code = code;
            Msg = msg;
            Data = data;
        }
    }

    public struct Result<T>
    {
        /// 
        /// 操作代码,默认200表示操作成功,500表示异常
        /// 
        public int Code;

        /// 
        /// 返回数据,强类型
        /// 
        public T Data;

        /// 
        /// 消息
        /// 
        public string Msg;

        public Result(T data)
        {
            Code = 200;
            Data = data;
            Msg = "操作成功";
        }
     
        public Result(string msg, int code = 500)
        {
            Code = code;
            Msg = msg;
            Data = default;
        }

        public Result(T data, int code = 200)
        {
            Code = code;
            Data = data;
            Msg = "操作成功";
        }

        public Result(T data, string msg = "", int code = 200)
        {
            Code = code;
            Msg = msg;
            Data = data;
        }
    }
}

数据层接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WebProjectNet7.ViewEntity;

namespace WebProjectNet7.IDAO
{
    /// 
    /// 数据接口基类
    /// 
    /// 
    public interface IDaoBase<T> where T : class
    {
        int Add(T entity);

        Task<int> AddAsync(T entity);

        int Add(IEnumerable<T> entitys);

        Task<int> AddListAsync(IEnumerable<T> entitys);

        int Update(T entity);

        Task<int> UpdateAsync(T entity);

        /// 
        /// 修改指定的字段
        /// 
        /// 
        /// 
        /// 
        Task<int> UpdateAsync(T entity, string[] column);

        /// 
        /// 异步修改集合,修改指定的列
        /// 
        /// 集合
        /// 指定的列,参考 id,name。要修改的列名传入数组
        /// 
        Task<int> UpdateListAsync(List<T> list, string[] column);

        /// 
        ///  [事务]批量修改或新增或删除(若干个)
        /// 
        /// 
        /// 
        Task<int> SaveMultipleAsync(List<SaveModel> list);

        /// 
        /// [事务] 批量保存或修改,要修改的列名中不要传入主键,新增的数据实体请将IsUpdate设置为false(默认修改操作)
        /// 新增数据可以不用传参数columns(要修改的列名称)
        /// 
        /// Entity类型
        /// Entity类型
        /// 要修改的Entity实体,必须
        /// 要修改的Entity实体,必须
        /// t1要修改的列名
        /// t2要修改的列名
        /// 
        Task<int> SaveMultipleAsync<T1, T2>(T1 t1, T2 t2, string[]? columns1=null, string[] columns2 = null) where T1 : class where T2 : class;

        /// 
        /// 批量修改 3个
        /// 
        /// 
        /// 
        /// 
        /// 要修改的Entity实体,必须
        /// 要修改的Entity实体,必须
        /// 要修改的Entity实体,必须
        /// 要修改的列名
        /// 要修改的列名
        /// 要修改的列名
        /// 
        Task<int> SaveMultipleAsync<T1, T2, T3>(T1 t1, T2 t2, T3 t3, string[] columns1, string[]? columns2, string[] columns3) where T1 : class where T2 : class where T3 : class;

        int Delete(T entity);

        /// 
        /// 根据主键删除一条
        /// 
        /// 主键值
        /// 
        Task<int> DeleteByPrimaryKeyAsync(object id);
        Task<int> DeleteAsync(T entity);
        int Delete(Expression<Func<T, bool>> where);
        Task<int> DeleteAsync(Expression<Func<T, bool>> where);

        /// 
        /// 根据主键查询一条
        /// 
        /// 主键
        /// 
        T Get(object id);

        /// 
        /// 根据主键异步查询
        /// 
        /// 主键
        /// 
        Task<T> GetAsync(object id);

        T Get(Expression<Func<T, bool>> where);

        /// 
        /// 异步查询单条记录
        /// 
        /// 
        /// 
        Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> where);

        IQueryable<T> GetList(Expression<Func<T, bool>> where);

        /// 
        /// 使用新的数据上下文
        /// 
        /// 
        /// 
        IQueryable<T> GetListByNewContext(Expression<Func<T, bool>> where);

        /// 
        /// 同步,查询表所有记录
        /// 
        /// 
        List<T> GetListAll();

        List<T> GetListAll(Expression<Func<T, bool>> where);

        /// 
        /// 异步查询集合
        /// 
        /// 条件
        /// 
        Task<List<T>> GetListAsync(Expression<Func<T, bool>> where);

        /// 
        /// 异步查询所有记录
        /// 
        /// 
        Task<List<T>> GetAllListAsync();

        IQueryable<T> GetQuery();
        IQueryable<T> GetQuery(Expression<Func<T, bool>> where);

        /// 
        /// 检查是否存在
        /// 
        /// 
        /// 
        bool Any(Expression<Func<T, bool>> where);

        /// 
        /// 检查是否存在
        /// 
        /// 
        /// 
        Task<bool> AnyAsync(Expression<Func<T, bool>> where);
        int Count(Expression<Func<T, bool>> where);
        Task<int> CountAsync(Expression<Func<T, bool>> where);

        PageModel<G> GetPage<G>(IQueryable<G> query, int pageIndex, int pageSize);
        PageModel<T> GetPage<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderwhere);

        /// 
        /// 异步,分页查询升序
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 2019-10-15 17:17:09 王浩力 添加
        Task<PageModel<T>> GetPageAsync<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderByAsc);

        /// 
        /// 异步分页,倒序查询
        /// 
        /// 
        /// 页码
        /// 每页记录数
        /// 查询条件
        /// 倒序列
        /// 
        Task<PageModel<T>> GetPageOrderByDescAsync<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderByDesc);

        /// 
        /// 表联合查询时,可用此方法
        /// 
        /// 视图实体类型,装了多个表字段的实体
        /// 
        /// 
        /// 
        /// 
        Task<PageModel<G>> GetPageAsync<G>(IQueryable<G> query, int pageIndex, int pageSize);

        /// 
        /// 扩展 IQueryable.ToListAsync();,此方法非常实用,可以在bll业务层使用
        /// 
        /// 
        /// 
        Task<List<G>> ToListAsync<G>(IQueryable<G> query);
    }
}


数据层接口实现

//功用:数据保存
//创建时间:2020-12-24 14:10:11
//作者:zzzzz
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Linq.Expressions;
using WebProjectNet7.DataBaseEntity;
using WebProjectNet7.DataBaseEntity.Tool;
using WebProjectNet7.IDAO;
using WebProjectNet7.ViewEntity;

namespace WebProjectNet7.IDAO_impl
{
    /// 
    /// 数据处理,实现
    /// 
    /// 
    public class DaoBase<T> : IDaoBase<T> where T : class
        //BaseEntity//,new()
    {
        /*
         * https://docs.microsoft.com/zh-cn/ef/core/dbcontext-configuration/#avoiding-dbcontext-threading-issues
         避免 DbContext 线程处理问题
Entity Framework Core 不支持在同一 DbContext 实例上运行多个并行操作。 这包括异步查询的并行执行以及从多个线程进行的任何显式并发使用。 因此,始终立即 await 异步调用,或对并行执行的操作使用单独的 DbContext 实例。
当 EF Core 检测到尝试同时使用 DbContext 实例的情况时,你将看到 InvalidOperationException,其中包含类似于以下内容的消息:
在上一个操作完成之前,第二个操作已在此上下文中启动。 这通常是由使用同一个 DbContext 实例的不同线程引起的,但不保证实例成员是线程安全的。
检测不到并发访问时,可能会导致未定义的行为、应用程序崩溃和数据损坏         
         */
        //每次查询使用新的DbContext,防止并发异常

        /// 
        /// ef数据上下文
        /// 
        private readonly DataContext dbContext;

        /// 
        /// 当前T类型对应的表
        /// 
        private readonly DbSet<T> dbSet;

        public DaoBase()
        {
            dbContext = new DataContext();
            dbSet = dbContext.Set<T>();
        }

        ///   
        /// 获取新的DbContext
        /// 
        /// 
        public DataContext GetNewDbContext()
        {
            return new DataContext();
        }

        /// 
        /// 获取没有上下文缓存的新查询
        /// 
        /// 
        protected IQueryable<T> GetDbsetNoCacheQueryable()
        {
            var db = GetNewDbContext();
            var dbSet2 = db.Set<T>();
            return dbSet2.AsNoTracking();
        }

        public int Add(T entity)
        {
            dbSet.Add(entity);
            return dbContext.SaveChanges();
        }

        public async Task<int> AddAsync(T entity)
        {
            dbSet.Add(entity);
            return await dbContext.SaveChangesAsync();
        }

        public int Add(IEnumerable<T> entitys)
        {
            foreach (var entity in entitys)
            {
                dbSet.Add(entity);
            }
            return dbContext.SaveChanges();
        }

        public async Task<int> AddListAsync(IEnumerable<T> entitys)
        {
            //  await dbSet.AddRangeAsync(entitys);
            dbSet.AddRange(entitys);
            return await dbContext.SaveChangesAsync();
        }

        public int Update(T entity)
        {
            DataContext dbContextUpdate = new DataContext();
            dbContextUpdate.Entry(entity).State = EntityState.Modified;
            return dbContextUpdate.SaveChanges();
        }

        public async Task<int> UpdateAsync(T entity)
        {
            try
            {
                DbContext dbContextUpdate = new DataContext();
                dbContextUpdate.Entry(entity).State = EntityState.Modified;
                return await dbContextUpdate.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return 0;
            }
        }

        public int Update(IEnumerable<T> entitys)
        {
            DbContext dbContextUpdate = new DataContext();
            foreach (var entity in entitys)
            {
                dbContextUpdate.Entry(entity).State = EntityState.Modified;
            }
            return dbContextUpdate.SaveChanges();
        }

        public async Task<int> UpdateAsync(T entity, string[] column)
        {
            DbContext dbContextUpdate = new DataContext();
            var entry = dbContextUpdate.Entry(entity);
            entry.State = EntityState.Modified;
            foreach (var item in column)
            {
                entry.Property(item).IsModified = true;
            }
            var listPv = entry.Properties.ToList();
            listPv.RemoveAll(w => w.Metadata.IsPrimaryKey());
            foreach (var item in listPv)
            {
                //字段名称 
                string itemName = item.Metadata.Name;
                if (column.Contains(itemName))
                {
                    continue;
                }
                entry.Property(itemName).IsModified = false;
            }
            return await dbContextUpdate.SaveChangesAsync();
        }

        /// 
        /// [事务]异步修改集合,修改指定的列
        /// 
        /// 集合
        /// 指定的列,参考 id,name。要修改的列名传入数组
        /// 
        public async Task<int> UpdateListAsync(List<T> list, string[] column)
        {
            DbContext dbContextUpdate = new DataContext();
            var tran = dbContextUpdate.Database.BeginTransaction();
            int count = 0;
            try
            {
                foreach (var entity in list)
                {
                    var entry = dbContextUpdate.Entry(entity);
                    entry.State = EntityState.Modified;
                    foreach (var item in column)
                    {
                        entry.Property(item).IsModified = true;
                    }
                    var listPv = entry.Properties.ToList();
                    listPv.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var item in listPv)
                    {
                        //字段名称
                        string itemName = item.Metadata.Name;
                        //bool isKey= item.Metadata.IsPrimaryKey();
                        //if (isKey)
                        //{
                        //    continue;
                        //}
                        if (column.Contains(itemName))
                        {
                            continue;
                        }
                        //item.IsModified = false;
                        entry.Property(itemName).IsModified = false;
                    }
                }
                count = await dbContextUpdate.SaveChangesAsync();
                tran.Commit();
            }
            catch (Exception)
            {
                tran.Rollback();
                throw;
            }
            finally
            {
                tran.Dispose();
            }
            return count;
        }

        /// 
        ///   [事务]批量修改或新增或删除(若干个)
        /// 
        /// 要操作的记录
        /// 
        public async Task<int> SaveMultipleAsync(List<SaveModel> list)
        {
            int count = 0;
            if (list == null || list.Count == 0)
            {
                return 0;
            }
            DbContext dbContextUpdate = new DataContext();
            IDbContextTransaction tran = null;
            try
            {
                tran = dbContextUpdate.Database.BeginTransaction();
                foreach (var item in list)
                {
                    var entityEntry = dbContextUpdate.Entry(item.Model);

                    //删除记录
                    if (item.IsDelete)
                    {
                        entityEntry.State = EntityState.Deleted;
                        continue;
                    }

                    //System.Reflection.PropertyInfo fieldInfo = item.ModelType.GetProperty("IsUpdate");
                    //bool isUpdate = Convert.ToBoolean(fieldInfo.GetValue(item.Model));
                    // if (isUpdate)
                    if (item.Columns != null && item.Columns.Length > 0)
                    {
                        //if (item.Columns == null || item.Columns.Count() == 0)
                        //{
                        //    throw new ArgumentNullException("修改时,必须传要修改的列,参数Columns必须");
                        //}

                        //修改记录
                        //var entityEntry = dbContextUpdate.Entry(item.Model);                    
                        entityEntry.State = EntityState.Modified;
                        foreach (var cols in item.Columns)
                        {
                            entityEntry.Property(cols).IsModified = true;
                        }
                        var listP2 = entityEntry.Properties.ToList();
                        listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                        foreach (var propertyN in listP2)
                        {
                            //字段名称
                            string itemName = propertyN.Metadata.Name;
                            if (item.Columns.Contains(itemName))
                            {
                                continue;
                            }
                            entityEntry.Property(itemName).IsModified = false;
                        }
                    }
                    else
                    {
                        //新增记录
                        dbContextUpdate.Add(item.Model);
                        //dbContextUpdate.Set(item.ModelType).Add(item.Model);
                        //dbContextUpdate.Set.Add(item.Model);
                    }
                }
                count = await dbContextUpdate.SaveChangesAsync();
                if (count > 0)
                {
                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                var ex2 = ex.InnerException ?? ex;
                ex2 = ex2.InnerException ?? ex2;
                LogHelpter.AddLog("SaveMultipleAsync(List list)执行异常:" + ex2.ToString());
                count = 0;
                tran.Rollback();
                throw ex2;
            }
            finally
            {
                tran.Dispose();
            }
            return count;
        }

        /// 
        /// 批量修改、新增
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task<int> SaveMultipleAsync<T1, T2>(T1 t1, T2 t2, string[]? columns1 = null, string[]? columns2 = null)
             where T1 : class
             where T2 : class
        {
            int count = 0;
            DbContext dbContextUpdate = new DataContext();
            IDbContextTransaction tran = null;
            try
            {
                tran = dbContextUpdate.Database.BeginTransaction();

                //第一个
                var entityEntry = dbContextUpdate.Entry(t1);
                if (columns1 != null && columns1.Length > 0)
                {
                    //修改记录                      
                    entityEntry.State = EntityState.Modified;
                    foreach (var cols in columns1)
                    {
                        entityEntry.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns1.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增          
                    dbContextUpdate.Add(t1);
                }

                //第二个
                var entityEntry2 = dbContextUpdate.Entry(t2);
                if (columns2 != null && columns2.Length > 0)
                {
                    //修改记录                      
                    entityEntry2.State = EntityState.Modified;
                    foreach (var cols in columns2)
                    {
                        entityEntry2.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry2.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns2.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry2.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增         
                    dbContextUpdate.Add(t2);
                }

                count = await dbContextUpdate.SaveChangesAsync();
                if (count > 0)
                {
                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                var ex2 = ex.InnerException ?? ex;
                ex2 = ex2.InnerException ?? ex2;
                LogHelpter.AddLog("SaveMultipleAsync(List list)执行异常:" + ex2.ToString(), null, "errorEF");
                count = 0;
                tran?.Rollback();
                throw ex2;
            }
            finally
            {
                tran?.Dispose();
                dbContextUpdate.Dispose();
            }
            return count;
        }

        /// 
        /// 批量修改、新增
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task<int> SaveMultipleAsync<T1, T2, T3>(T1 t1, T2 t2, T3 t3, string[] columns1, string[] columns2, string[] columns3)
           where T1 : class
           where T2 : class
           where T3 : class
        {
            int count = 0;
            DbContext dbContextUpdate = new DataContext();
            IDbContextTransaction tran = null;
            try
            {
                tran = dbContextUpdate.Database.BeginTransaction();

                //第一个
                var entityEntry = dbContextUpdate.Entry(t1);
                if (columns1 != null && columns1.Length > 0)
                {
                    //修改记录                      
                    entityEntry.State = EntityState.Modified;
                    foreach (var cols in columns1)
                    {
                        entityEntry.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns1.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增
                    dbContextUpdate.Add(t1);
                }


                //第二个
                var entityEntry2 = dbContextUpdate.Entry(t2);
                if (columns2 != null && columns2.Length > 0)
                {
                    //修改记录                      
                    entityEntry2.State = EntityState.Modified;
                    foreach (var cols in columns2)
                    {
                        entityEntry2.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry2.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns2.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry2.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增
                    dbContextUpdate.Add(t2);
                }

                //第3个
                var entityEntry3 = dbContextUpdate.Entry(t3);
                if (columns3 != null && columns3.Length > 0)
                {
                    //修改记录                      
                    entityEntry3.State = EntityState.Modified;
                    foreach (var cols in columns3)
                    {
                        entityEntry3.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry3.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns3.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry3.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增
                    dbContextUpdate.Add(t3);
                }

                count = await dbContextUpdate.SaveChangesAsync();
                if (count > 0)
                {
                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                var ex2 = ex.InnerException ?? ex;
                ex2 = ex2.InnerException ?? ex2;
                LogHelpter.AddLog("SaveMultipleAsync(List list)执行异常:" + ex2.ToString(), null, "errorEF");
                count = 0;
                tran?.Rollback();
                throw ex2;
            }
            finally
            {
                tran?.Dispose();
                dbContextUpdate.Dispose();
            }
            return count;
        }

        public int Delete(T entity)
        {
            dbSet.Attach(entity);
            dbSet.Remove(entity);
            return dbContext.SaveChanges();
        }

        public async Task<int> DeleteByPrimaryKeyAsync(object id)
        {
            DataContext DataContext = new DataContext();
            var entityEntry = DataContext.Set<T>();
            Microsoft.EntityFrameworkCore.Metadata.IKey key = entityEntry.EntityType.FindPrimaryKey();
            var list = key.Properties;
            var first = list.First();
            //表名
            string tableName = key.DeclaringEntityType.ClrType.Name;
            //字段类型
            string typeName = first.ClrType.Name;
            //字段名称
            string keyName = first.Name;
            string sql = string.Empty;
            switch (typeName)
            {
                case "String":
                case "Guid":
                    sql = $"delete from [{tableName}]  where [{keyName}]='{id}';";
                    break;
                case "Int64":
                case "Int32":
                    sql = $"delete from [{tableName}] where [{keyName}]={id};";
                    break;
                default:
                    throw new DbUpdateException("没有分析出主键,无法删除数据");
                    //break;
            }
            int count = await DataContext.Database.ExecuteSqlRawAsync(sql);
            return count;
        }

        public async Task<int> DeleteAsync(T entity)
        {
            //dbSet.Attach(entity);
            //dbSet.Remove(entity);
            //return await dbContext.SaveChangesAsync();

            DbContext dbContextUpdate = new DataContext();
            dbContextUpdate.Set<T>().Attach(entity);
            dbContextUpdate.Set<T>().Remove(entity);
            return await dbContextUpdate.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(Expression<Func<T, bool>> where)
        {
            DbContext currentContext = new DataContext();
            var entitys = await dbSet.Where(where).ToListAsync();
            currentContext.Set<T>().RemoveRange(entitys);
            return await currentContext.SaveChangesAsync();
        }


        public int Delete(Expression<Func<T, bool>> where)
        {
            var entitys = this.GetList(where);
            foreach (var entity in entitys)
            {
                dbSet.Remove(entity);
            }
            return dbContext.SaveChanges();
        }


        public T Get(Expression<Func<T, bool>> where)
        {
            DataContext dbContext = GetNewDbContext();
            return dbContext.Set<T>().AsNoTracking().Where(where).FirstOrDefault();
        }

        /// 
        ///根据主键查询
        /// 
        /// 主键
        /// 
        public T Get(object id)
        {
            DataContext dbContext = GetNewDbContext();
            var model = dbContext.Set<T>().Find(id);
            //var model = dbSet.Find(id);
            if (model != null)
            {
                //设置不跟踪上下文实体,有利于修改数据保存
                var entity = dbContext.Entry(model);
                entity.State = EntityState.Detached;
            }
            return model;
        }

        /// 
        ///根据主键异步查询
        /// 
        /// 主键
        /// 
        public async Task<T> GetAsync(object id)
        {
            DataContext dbContext = GetNewDbContext();
            var model = await dbContext.Set<T>().FindAsync(id);
            if (model != null)
            {
                //设置不跟踪上下文实体,有利于修改数据保存
                var entity = dbContext.Entry(model);
                if (entity.State == EntityState.Unchanged)
                {
                    entity.State = EntityState.Detached;
                }
            }
            return model;
        }

        public async Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> where)
        {
            //修改时间:2023-10-17 20:05:14,王浩力
            //DataContext dbContext = GetNewDbContext();
            //return await dbContext.Set().AsNoTracking().FirstOrDefaultAsync(where);
            return await GetDbsetNoCacheQueryable().FirstOrDefaultAsync(where);
        }

        public List<T> GetListAll()
        {
            return GetDbsetNoCacheQueryable().ToList();
        }

        public List<T> GetListAll(Expression<Func<T, bool>> where)
        {
            return GetDbsetNoCacheQueryable().Where(where).ToList();
        }

        public IQueryable<T> GetList(Expression<Func<T, bool>> where)
        {
            if (where == null) return GetDbsetNoCacheQueryable();
            return GetDbsetNoCacheQueryable().Where(where);
        }

        public IQueryable<T> GetListByNewContext(Expression<Func<T, bool>> where)
        {
            DbContext dataContext = new DataContext();
            if (where == null) return dataContext.Set<T>().AsNoTracking();
            return dataContext.Set<T>().AsNoTracking().Where(where);
        }

        public IQueryable<T> GetQuery()
        {
            return GetDbsetNoCacheQueryable();
        }

        public IQueryable<T> GetQuery(Expression<Func<T, bool>> where)
        {
            if (where == null) return GetDbsetNoCacheQueryable();
            return GetDbsetNoCacheQueryable().Where(where);
        }

        public async Task<List<T>> GetListAsync(Expression<Func<T, bool>> where)
        {
            //DataContext dbContext = GetNewDbContext();
            //var list = await dbContext.Set().Where(where).ToListAsync();

            var list = await GetDbsetNoCacheQueryable().Where(where).ToListAsync();
            return list;
        }

        public async Task<List<T>> GetAllListAsync()
        {
            return await GetDbsetNoCacheQueryable().ToListAsync();
        }

        public bool Any(Expression<Func<T, bool>> @where)
        {
            return GetDbsetNoCacheQueryable().Any(where);
        }

        public async Task<bool> AnyAsync(Expression<Func<T, bool>> where)
        {
            return await GetDbsetNoCacheQueryable().AnyAsync(where);
        }

        public int Count(Expression<Func<T, bool>> @where)
        {
            return GetDbsetNoCacheQueryable().Count(where);
        }

        public async Task<int> CountAsync(Expression<Func<T, bool>> where)
        {
            int count = await GetDbsetNoCacheQueryable().Where(where).CountAsync();
            return count;
        }

        /// 
        /// 分页排序查询
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public PageModel<T> GetPage<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderwhere)
        {
            int count = GetDbsetNoCacheQueryable().Where(where).Count();
            var list = GetDbsetNoCacheQueryable().Where(where).OrderBy(orderwhere).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return new PageModel<T>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 表联合查询时,可用此方法
        /// 
        /// 视图实体类型,装了多个表字段的实体
        /// 
        /// 
        /// 
        /// 
        public PageModel<G> GetPage<G>(IQueryable<G> query, int pageIndex, int pageSize)
        {
            int count = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return new PageModel<G>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 表联合查询时,可用此方法
        /// 
        /// 视图实体类型,装了多个表字段的实体
        /// 
        /// 
        /// 
        /// 
        public async Task<PageModel<G>> GetPageAsync<G>(IQueryable<G> query, int pageIndex, int pageSize)
        {
            int count = await query.CountAsync();
            var list = await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<G>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 当前实体类型的分页
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task<PageModel<T>> GetPageAsync<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderByAsc)
        {
            int count = await GetDbsetNoCacheQueryable().Where(where).CountAsync();
            var list = await GetDbsetNoCacheQueryable().Where(where).OrderBy(orderByAsc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<T>(list, count, pageIndex, pageSize);
        }

        public async Task<PageModel<T>> GetPageOrderByDescAsync<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderByDesc)
        {
            int count = await GetDbsetNoCacheQueryable().Where(where).CountAsync();
            var list = await GetDbsetNoCacheQueryable().Where(where).OrderByDescending(orderByDesc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<T>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 扩展 IQueryable.ToListAsync();
        /// 
        /// 
        /// 
        public async Task<List<G>> ToListAsync<G>(IQueryable<G> query)
        {
            var list = await query.ToListAsync();
            return list;
        }


    }
}


数据层具体示例

//功用:操作日志保存
//创建时间:2021-9-14 10:41:42
//作者:王浩力

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong.IDAL
{
    /// 
    /// 操作日志保存
    /// 
    public interface IOperate_logDAL : IDaoBase<Operate_log>
    {
        /// 
        /// 新增操作记录,用户只需要传入用户id
        /// 
        /// 
        /// 
        /// 创建时间:2021-9-14 10:51:35 
        /// 
        void AddOperateLog(Operate_log operate_Log);

    }
}

//功用: 操作日志,数据保存
//创建时间:2021-9-14 10:54:00
//作者:王浩力

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.IDAL;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong.DAL_Impl
{
    /// 
    /// 操作日志,数据保存
    /// 
    public class Operate_logDALImpl : DaoBase<Operate_log>, IOperate_logDAL
    {

        public void AddOperateLog(Operate_log operate_Log)
        {
            if (operate_Log == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(operate_Log.Operate_user_id))
            {
                return;
            }
            Task.Run(async () =>
            {
                MyDbContext myDbContext = null;
                try
                {
                    operate_Log.Id = Guid.NewGuid().ToString("n");
                    operate_Log.Create_time = DateTime.Now;

                    myDbContext = new MyDbContext();

                    string departmentId = string.Empty;

                    //查询用户姓名 
                    if (operate_Log.User_type == 1)
                    {
                        //web管理系统用户
                        var user = await myDbContext.Sys_manager.FirstOrDefaultAsync(x => x.Sys_manager_id == operate_Log.Operate_user_id);
                        operate_Log.Operate_real_name = user?.Realname;
                    }
                    else
                    {
                        //WPF登录用户
                        var user = await myDbContext.Person.FirstOrDefaultAsync(x => x.Person_id == operate_Log.Operate_user_id);
                        operate_Log.Operate_real_name = user?.Real_name;
                        departmentId = user?.Department_id;
                    }

                    //查询部门
                    if (operate_Log.User_type==2)
                    {
                        var dep = await myDbContext.Department.FirstOrDefaultAsync(x => x.Id == departmentId);
                        operate_Log.Department_name = dep?.Department_name;
                    }              

                    await myDbContext.AddAsync(operate_Log);
                    await myDbContext.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    myDbContext?.DisposeAsync();
                }
            });



        }
    }
}

业务层调用:

//功用:项目业务处理
//创建时间:2021-9-14 10:26:09 
//作者:王浩力

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong.IBusiness
{
    public interface IProjectBusiness
    {
        /// 
        /// 保存 停电范围图片
        /// 
        /// 
        /// 
        /// 
        /// 创建时间:2021-9-28 16:02:45
        /// 
        public Task<Result> AddProject_power_cutAsync(Project_power_cut power_Cut);

        /// 
        /// 保存用户导入的地图到项目信息
        /// 
        /// 图片id
        /// 项目id
        /// 当前登录用户id
        /// 
        /// 
        /// 创建时间:2021-9-14 11:00:36
        /// 
        Task<Result> SaveBackgroundImg(string imgId,string projectId,string loginUserId);

        /// 
        /// WPF端,导入工人
        /// 
        /// 导入的excel文件流
        /// 当前登录用户id
        /// 
        /// 
        /// 创建时间:2021-9-14 15:50:06
        /// 测试通过:2021-9-16 14:10:32
        /// 
        Task<Result> ImportWorker(System.IO.Stream stream,string loginUserId, string departmentId, string projectId);

        /// 
        /// 项目分页
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 创建时间:2021-9-13 17:58:01
        /// 
        Task<PageModel<Project>> PageProject(Project project, int p, int rows);

        /// 
        /// 根据主键获取项目信息
        /// 
        /// 项目主键
        /// 
        /// 
        /// 创建时间:2021-9-13 17:59:05
        /// 
        Task<Project> GetProject(string id);

        /// 
        /// 批量保存安全警示图片
        /// 
        /// 安全警示图片多个
        /// WPF端当前登录人id
        /// 
        /// 
        /// 创建时间:2021-9-24 11:18:54
        /// 
        Task<Result> SaveListSafety_warningImg(List<Safety_warning> list, string loginUserId);

        /// 
        /// 批量保存检修工艺图片
        /// 
        /// 检修工艺图片,多个
        /// WPF端当前登录人id
        /// 
        /// 
        /// 创建时间:2021-9-24 11:18:54
        /// 
        Task<Result> SaveListOverhaul(List<Overhaul> list, string loginUserId);

        /// 
        /// 根据项目id查询下面的检修工艺图片
        /// 
        /// 项目id
        /// 
        /// 
        /// 创建时间:2021-9-24 14:07:24
        /// 
        Task<List<Overhaul>> GetOverhauls(string projectId);

        /// 
        /// 根据项目id查询下面安全警示图片
        /// 
        /// 项目id
        /// 
        /// 
        /// 创建时间:2021-9-24 14:08:08
        /// 
        Task<List<Safety_warning>> GetListSafety_warningImg(string projectId);

        /// 
        /// 项目勾选的的视频列表,保存
        /// 
        /// 视频列表
        /// 
        /// 
        /// 创建时间:2021-9-29 10:26:54
        /// 
        Task<Result> SaveProjectSelectedVideoList(List<Station_video> list);

    }
}

数据层接口,实现

//功用:数据保存
//创建时间:2020-12-24 14:10:11
//作者:王浩力
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Linq.Expressions;
using WebProjectNet7.DataBaseEntity;
using WebProjectNet7.DataBaseEntity.Tool;
using WebProjectNet7.IDAO;
using WebProjectNet7.ViewEntity;

namespace WebProjectNet7.IDAO_impl
{
    /// 
    /// 数据处理,实现
    /// 
    /// 
    public class DaoBase<T> : IDaoBase<T> where T : class
        //BaseEntity//,new()
    {
        /*
         * https://docs.microsoft.com/zh-cn/ef/core/dbcontext-configuration/#avoiding-dbcontext-threading-issues
         避免 DbContext 线程处理问题
Entity Framework Core 不支持在同一 DbContext 实例上运行多个并行操作。 这包括异步查询的并行执行以及从多个线程进行的任何显式并发使用。 因此,始终立即 await 异步调用,或对并行执行的操作使用单独的 DbContext 实例。
当 EF Core 检测到尝试同时使用 DbContext 实例的情况时,你将看到 InvalidOperationException,其中包含类似于以下内容的消息:
在上一个操作完成之前,第二个操作已在此上下文中启动。 这通常是由使用同一个 DbContext 实例的不同线程引起的,但不保证实例成员是线程安全的。
检测不到并发访问时,可能会导致未定义的行为、应用程序崩溃和数据损坏         
         */
        //每次查询使用新的DbContext,防止并发异常

        /// 
        /// ef数据上下文
        /// 
        private readonly DataContext dbContext;

        /// 
        /// 当前T类型对应的表
        /// 
        private readonly DbSet<T> dbSet;

        public DaoBase()
        {
            dbContext = new DataContext();
            dbSet = dbContext.Set<T>();
        }

        ///   
        /// 获取新的DbContext
        /// 
        /// 
        public DataContext GetNewDbContext()
        {
            return new DataContext();
        }

        /// 
        /// 获取没有上下文缓存的新查询
        /// 
        /// 
        protected IQueryable<T> GetDbsetNoCacheQueryable()
        {
            var db = GetNewDbContext();
            var dbSet2 = db.Set<T>();
            return dbSet2.AsNoTracking();
        }

        public int Add(T entity)
        {
            dbSet.Add(entity);
            return dbContext.SaveChanges();
        }

        public async Task<int> AddAsync(T entity)
        {
            dbSet.Add(entity);
            return await dbContext.SaveChangesAsync();
        }

        public int Add(IEnumerable<T> entitys)
        {
            foreach (var entity in entitys)
            {
                dbSet.Add(entity);
            }
            return dbContext.SaveChanges();
        }

        public async Task<int> AddListAsync(IEnumerable<T> entitys)
        {
            //  await dbSet.AddRangeAsync(entitys);
            dbSet.AddRange(entitys);
            return await dbContext.SaveChangesAsync();
        }

        public int Update(T entity)
        {
            DataContext dbContextUpdate = new DataContext();
            dbContextUpdate.Entry(entity).State = EntityState.Modified;
            return dbContextUpdate.SaveChanges();
        }

        public async Task<int> UpdateAsync(T entity)
        {
            try
            {
                DbContext dbContextUpdate = new DataContext();
                dbContextUpdate.Entry(entity).State = EntityState.Modified;
                return await dbContextUpdate.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return 0;
            }
        }

        public int Update(IEnumerable<T> entitys)
        {
            DbContext dbContextUpdate = new DataContext();
            foreach (var entity in entitys)
            {
                dbContextUpdate.Entry(entity).State = EntityState.Modified;
            }
            return dbContextUpdate.SaveChanges();
        }

        public async Task<int> UpdateAsync(T entity, string[] column)
        {
            DbContext dbContextUpdate = new DataContext();
            var entry = dbContextUpdate.Entry(entity);
            entry.State = EntityState.Modified;
            foreach (var item in column)
            {
                entry.Property(item).IsModified = true;
            }
            var listPv = entry.Properties.ToList();
            listPv.RemoveAll(w => w.Metadata.IsPrimaryKey());
            foreach (var item in listPv)
            {
                //字段名称 
                string itemName = item.Metadata.Name;
                if (column.Contains(itemName))
                {
                    continue;
                }
                entry.Property(itemName).IsModified = false;
            }
            return await dbContextUpdate.SaveChangesAsync();
        }

        /// 
        /// [事务]异步修改集合,修改指定的列
        /// 
        /// 集合
        /// 指定的列,参考 id,name。要修改的列名传入数组
        /// 
        public async Task<int> UpdateListAsync(List<T> list, string[] column)
        {
            DbContext dbContextUpdate = new DataContext();
            var tran = dbContextUpdate.Database.BeginTransaction();
            int count = 0;
            try
            {
                foreach (var entity in list)
                {
                    var entry = dbContextUpdate.Entry(entity);
                    entry.State = EntityState.Modified;
                    foreach (var item in column)
                    {
                        entry.Property(item).IsModified = true;
                    }
                    var listPv = entry.Properties.ToList();
                    listPv.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var item in listPv)
                    {
                        //字段名称
                        string itemName = item.Metadata.Name;
                        //bool isKey= item.Metadata.IsPrimaryKey();
                        //if (isKey)
                        //{
                        //    continue;
                        //}
                        if (column.Contains(itemName))
                        {
                            continue;
                        }
                        //item.IsModified = false;
                        entry.Property(itemName).IsModified = false;
                    }
                }
                count = await dbContextUpdate.SaveChangesAsync();
                tran.Commit();
            }
            catch (Exception)
            {
                tran.Rollback();
                throw;
            }
            finally
            {
                tran.Dispose();
            }
            return count;
        }

        /// 
        ///   [事务]批量修改或新增或删除(若干个)
        /// 
        /// 要操作的记录
        /// 
        public async Task<int> SaveMultipleAsync(List<SaveModel> list)
        {
            int count = 0;
            if (list == null || list.Count == 0)
            {
                return 0;
            }
            DbContext dbContextUpdate = new DataContext();
            IDbContextTransaction tran = null;
            try
            {
                tran = dbContextUpdate.Database.BeginTransaction();
                foreach (var item in list)
                {
                    var entityEntry = dbContextUpdate.Entry(item.Model);

                    //删除记录
                    if (item.IsDelete)
                    {
                        entityEntry.State = EntityState.Deleted;
                        continue;
                    }

                    //System.Reflection.PropertyInfo fieldInfo = item.ModelType.GetProperty("IsUpdate");
                    //bool isUpdate = Convert.ToBoolean(fieldInfo.GetValue(item.Model));
                    // if (isUpdate)
                    if (item.Columns != null && item.Columns.Length > 0)
                    {
                        //if (item.Columns == null || item.Columns.Count() == 0)
                        //{
                        //    throw new ArgumentNullException("修改时,必须传要修改的列,参数Columns必须");
                        //}

                        //修改记录
                        //var entityEntry = dbContextUpdate.Entry(item.Model);                    
                        entityEntry.State = EntityState.Modified;
                        foreach (var cols in item.Columns)
                        {
                            entityEntry.Property(cols).IsModified = true;
                        }
                        var listP2 = entityEntry.Properties.ToList();
                        listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                        foreach (var propertyN in listP2)
                        {
                            //字段名称
                            string itemName = propertyN.Metadata.Name;
                            if (item.Columns.Contains(itemName))
                            {
                                continue;
                            }
                            entityEntry.Property(itemName).IsModified = false;
                        }
                    }
                    else
                    {
                        //新增记录
                        dbContextUpdate.Add(item.Model);
                        //dbContextUpdate.Set(item.ModelType).Add(item.Model);
                        //dbContextUpdate.Set.Add(item.Model);
                    }
                }
                count = await dbContextUpdate.SaveChangesAsync();
                if (count > 0)
                {
                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                var ex2 = ex.InnerException ?? ex;
                ex2 = ex2.InnerException ?? ex2;
                LogHelpter.AddLog("SaveMultipleAsync(List list)执行异常:" + ex2.ToString());
                count = 0;
                tran.Rollback();
                throw ex2;
            }
            finally
            {
                tran.Dispose();
            }
            return count;
        }

        /// 
        /// 批量修改、新增
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task<int> SaveMultipleAsync<T1, T2>(T1 t1, T2 t2, string[]? columns1 = null, string[]? columns2 = null)
             where T1 : class
             where T2 : class
        {
            int count = 0;
            DbContext dbContextUpdate = new DataContext();
            IDbContextTransaction tran = null;
            try
            {
                tran = dbContextUpdate.Database.BeginTransaction();

                //第一个
                var entityEntry = dbContextUpdate.Entry(t1);
                if (columns1 != null && columns1.Length > 0)
                {
                    //修改记录                      
                    entityEntry.State = EntityState.Modified;
                    foreach (var cols in columns1)
                    {
                        entityEntry.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns1.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增          
                    dbContextUpdate.Add(t1);
                }

                //第二个
                var entityEntry2 = dbContextUpdate.Entry(t2);
                if (columns2 != null && columns2.Length > 0)
                {
                    //修改记录                      
                    entityEntry2.State = EntityState.Modified;
                    foreach (var cols in columns2)
                    {
                        entityEntry2.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry2.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns2.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry2.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增         
                    dbContextUpdate.Add(t2);
                }

                count = await dbContextUpdate.SaveChangesAsync();
                if (count > 0)
                {
                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                var ex2 = ex.InnerException ?? ex;
                ex2 = ex2.InnerException ?? ex2;
                LogHelpter.AddLog("SaveMultipleAsync(List list)执行异常:" + ex2.ToString(), null, "errorEF");
                count = 0;
                tran?.Rollback();
                throw ex2;
            }
            finally
            {
                tran?.Dispose();
                dbContextUpdate.Dispose();
            }
            return count;
        }

        /// 
        /// 批量修改、新增
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task<int> SaveMultipleAsync<T1, T2, T3>(T1 t1, T2 t2, T3 t3, string[] columns1, string[] columns2, string[] columns3)
           where T1 : class
           where T2 : class
           where T3 : class
        {
            int count = 0;
            DbContext dbContextUpdate = new DataContext();
            IDbContextTransaction tran = null;
            try
            {
                tran = dbContextUpdate.Database.BeginTransaction();

                //第一个
                var entityEntry = dbContextUpdate.Entry(t1);
                if (columns1 != null && columns1.Length > 0)
                {
                    //修改记录                      
                    entityEntry.State = EntityState.Modified;
                    foreach (var cols in columns1)
                    {
                        entityEntry.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns1.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增
                    dbContextUpdate.Add(t1);
                }


                //第二个
                var entityEntry2 = dbContextUpdate.Entry(t2);
                if (columns2 != null && columns2.Length > 0)
                {
                    //修改记录                      
                    entityEntry2.State = EntityState.Modified;
                    foreach (var cols in columns2)
                    {
                        entityEntry2.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry2.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns2.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry2.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增
                    dbContextUpdate.Add(t2);
                }

                //第3个
                var entityEntry3 = dbContextUpdate.Entry(t3);
                if (columns3 != null && columns3.Length > 0)
                {
                    //修改记录                      
                    entityEntry3.State = EntityState.Modified;
                    foreach (var cols in columns3)
                    {
                        entityEntry3.Property(cols).IsModified = true;
                    }
                    var listP2 = entityEntry3.Properties.ToList();
                    listP2.RemoveAll(w => w.Metadata.IsPrimaryKey());
                    foreach (var propertyN in listP2)
                    {
                        //字段名称
                        string itemName = propertyN.Metadata.Name;
                        if (columns3.Contains(itemName))
                        {
                            continue;
                        }
                        entityEntry3.Property(itemName).IsModified = false;
                    }
                }
                else
                {
                    //新增
                    dbContextUpdate.Add(t3);
                }

                count = await dbContextUpdate.SaveChangesAsync();
                if (count > 0)
                {
                    tran.Commit();
                }
            }
            catch (Exception ex)
            {
                var ex2 = ex.InnerException ?? ex;
                ex2 = ex2.InnerException ?? ex2;
                LogHelpter.AddLog("SaveMultipleAsync(List list)执行异常:" + ex2.ToString(), null, "errorEF");
                count = 0;
                tran?.Rollback();
                throw ex2;
            }
            finally
            {
                tran?.Dispose();
                dbContextUpdate.Dispose();
            }
            return count;
        }

        public int Delete(T entity)
        {
            dbSet.Attach(entity);
            dbSet.Remove(entity);
            return dbContext.SaveChanges();
        }

        public async Task<int> DeleteByPrimaryKeyAsync(object id)
        {
            DataContext DataContext = new DataContext();
            var entityEntry = DataContext.Set<T>();
            Microsoft.EntityFrameworkCore.Metadata.IKey key = entityEntry.EntityType.FindPrimaryKey();
            var list = key.Properties;
            var first = list.First();
            //表名
            string tableName = key.DeclaringEntityType.ClrType.Name;
            //字段类型
            string typeName = first.ClrType.Name;
            //字段名称
            string keyName = first.Name;
            string sql = string.Empty;
            switch (typeName)
            {
                case "String":
                case "Guid":
                    sql = $"delete from [{tableName}]  where [{keyName}]='{id}';";
                    break;
                case "Int64":
                case "Int32":
                    sql = $"delete from [{tableName}] where [{keyName}]={id};";
                    break;
                default:
                    throw new DbUpdateException("没有分析出主键,无法删除数据");
                    //break;
            }
            int count = await DataContext.Database.ExecuteSqlRawAsync(sql);
            return count;
        }

        public async Task<int> DeleteAsync(T entity)
        {
            //dbSet.Attach(entity);
            //dbSet.Remove(entity);
            //return await dbContext.SaveChangesAsync();

            DbContext dbContextUpdate = new DataContext();
            dbContextUpdate.Set<T>().Attach(entity);
            dbContextUpdate.Set<T>().Remove(entity);
            return await dbContextUpdate.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(Expression<Func<T, bool>> where)
        {
            DbContext currentContext = new DataContext();
            var entitys = await dbSet.Where(where).ToListAsync();
            currentContext.Set<T>().RemoveRange(entitys);
            return await currentContext.SaveChangesAsync();
        }


        public int Delete(Expression<Func<T, bool>> where)
        {
            var entitys = this.GetList(where);
            foreach (var entity in entitys)
            {
                dbSet.Remove(entity);
            }
            return dbContext.SaveChanges();
        }


        public T Get(Expression<Func<T, bool>> where)
        {
            DataContext dbContext = GetNewDbContext();
            return dbContext.Set<T>().AsNoTracking().Where(where).FirstOrDefault();
        }

        /// 
        ///根据主键查询
        /// 
        /// 主键
        /// 
        public T Get(object id)
        {
            DataContext dbContext = GetNewDbContext();
            var model = dbContext.Set<T>().Find(id);
            //var model = dbSet.Find(id);
            if (model != null)
            {
                //设置不跟踪上下文实体,有利于修改数据保存
                var entity = dbContext.Entry(model);
                entity.State = EntityState.Detached;
            }
            return model;
        }

        /// 
        ///根据主键异步查询
        /// 
        /// 主键
        /// 
        public async Task<T> GetAsync(object id)
        {
            DataContext dbContext = GetNewDbContext();
            var model = await dbContext.Set<T>().FindAsync(id);
            if (model != null)
            {
                //设置不跟踪上下文实体,有利于修改数据保存
                var entity = dbContext.Entry(model);
                if (entity.State == EntityState.Unchanged)
                {
                    entity.State = EntityState.Detached;
                }
            }
            return model;
        }

        public async Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> where)
        {
            //修改时间:2023-10-17 20:05:14,王浩力
            //DataContext dbContext = GetNewDbContext();
            //return await dbContext.Set().AsNoTracking().FirstOrDefaultAsync(where);
            return await GetDbsetNoCacheQueryable().FirstOrDefaultAsync(where);
        }

        public List<T> GetListAll()
        {
            return GetDbsetNoCacheQueryable().ToList();
        }

        public List<T> GetListAll(Expression<Func<T, bool>> where)
        {
            return GetDbsetNoCacheQueryable().Where(where).ToList();
        }

        public IQueryable<T> GetList(Expression<Func<T, bool>> where)
        {
            if (where == null) return GetDbsetNoCacheQueryable();
            return GetDbsetNoCacheQueryable().Where(where);
        }

        public IQueryable<T> GetListByNewContext(Expression<Func<T, bool>> where)
        {
            DbContext dataContext = new DataContext();
            if (where == null) return dataContext.Set<T>().AsNoTracking();
            return dataContext.Set<T>().AsNoTracking().Where(where);
        }

        public IQueryable<T> GetQuery()
        {
            return GetDbsetNoCacheQueryable();
        }

        public IQueryable<T> GetQuery(Expression<Func<T, bool>> where)
        {
            if (where == null) return GetDbsetNoCacheQueryable();
            return GetDbsetNoCacheQueryable().Where(where);
        }

        public async Task<List<T>> GetListAsync(Expression<Func<T, bool>> where)
        {
            //DataContext dbContext = GetNewDbContext();
            //var list = await dbContext.Set().Where(where).ToListAsync();

            var list = await GetDbsetNoCacheQueryable().Where(where).ToListAsync();
            return list;
        }

        public async Task<List<T>> GetAllListAsync()
        {
            return await GetDbsetNoCacheQueryable().ToListAsync();
        }

        public bool Any(Expression<Func<T, bool>> @where)
        {
            return GetDbsetNoCacheQueryable().Any(where);
        }

        public async Task<bool> AnyAsync(Expression<Func<T, bool>> where)
        {
            return await GetDbsetNoCacheQueryable().AnyAsync(where);
        }

        public int Count(Expression<Func<T, bool>> @where)
        {
            return GetDbsetNoCacheQueryable().Count(where);
        }

        public async Task<int> CountAsync(Expression<Func<T, bool>> where)
        {
            int count = await GetDbsetNoCacheQueryable().Where(where).CountAsync();
            return count;
        }

        /// 
        /// 分页排序查询
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public PageModel<T> GetPage<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderwhere)
        {
            int count = GetDbsetNoCacheQueryable().Where(where).Count();
            var list = GetDbsetNoCacheQueryable().Where(where).OrderBy(orderwhere).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return new PageModel<T>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 表联合查询时,可用此方法
        /// 
        /// 视图实体类型,装了多个表字段的实体
        /// 
        /// 
        /// 
        /// 
        public PageModel<G> GetPage<G>(IQueryable<G> query, int pageIndex, int pageSize)
        {
            int count = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return new PageModel<G>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 表联合查询时,可用此方法
        /// 
        /// 视图实体类型,装了多个表字段的实体
        /// 
        /// 
        /// 
        /// 
        public async Task<PageModel<G>> GetPageAsync<G>(IQueryable<G> query, int pageIndex, int pageSize)
        {
            int count = await query.CountAsync();
            var list = await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<G>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 当前实体类型的分页
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task<PageModel<T>> GetPageAsync<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderByAsc)
        {
            int count = await GetDbsetNoCacheQueryable().Where(where).CountAsync();
            var list = await GetDbsetNoCacheQueryable().Where(where).OrderBy(orderByAsc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<T>(list, count, pageIndex, pageSize);
        }

        public async Task<PageModel<T>> GetPageOrderByDescAsync<SortKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, Expression<Func<T, SortKey>> orderByDesc)
        {
            int count = await GetDbsetNoCacheQueryable().Where(where).CountAsync();
            var list = await GetDbsetNoCacheQueryable().Where(where).OrderByDescending(orderByDesc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<T>(list, count, pageIndex, pageSize);
        }

        /// 
        /// 扩展 IQueryable.ToListAsync();
        /// 
        /// 
        /// 
        public async Task<List<G>> ToListAsync<G>(IQueryable<G> query)
        {
            var list = await query.ToListAsync();
            return list;
        }


    }
}

//功用:项目接口实现
//创建时间:2021-9-14 10:32:26
//作者:xxxx

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.IBusiness;
using WebMvcNetCore.TuShi.FenGong.IDAL;
using WebMvcNetCore.TuShi.FenGong.Model;
using WebMvcNetCore.TuShi.FenGong.Model.Tool;

namespace WebMvcNetCore.TuShi.FenGong.BusinessImpl
{
    /// 
    /// 项目接口实现
    /// 
    public class ProjectBusinessImpl : IProjectBusiness
    {
        readonly IProjectDAL projectDAL;
        readonly IOperate_logDAL operate_LogDAL;
        readonly IWorkerDAL workerDAL;
        readonly IOverhaulDAL overhaulDAL;
        readonly ISafety_warningDAL safety_WarningDAL;
        readonly IUpload_imgDAL upload_ImgDAL;
        readonly IProject_power_cutDAL project_Power_CutDAL;
        readonly IPersonDAL personDAL;
        readonly IStation_videoDAL station_VideoDAL;

        public ProjectBusinessImpl(IProjectDAL _projectDAL, IOperate_logDAL _operate_LogDAL
            , IOverhaulDAL _overhaulDAL
            , ISafety_warningDAL _safety_WarningDAL
            , IUpload_imgDAL _upload_ImgDAL
            , IPersonDAL _personDAL
            , IProject_power_cutDAL _project_Power_CutDAL
            , IStation_videoDAL _station_VideoDAL
            , IWorkerDAL _workerDAL)
        {
            station_VideoDAL = _station_VideoDAL;
            projectDAL = _projectDAL;
            operate_LogDAL = _operate_LogDAL;
            workerDAL = _workerDAL;
            overhaulDAL = _overhaulDAL;
            safety_WarningDAL = _safety_WarningDAL;
            upload_ImgDAL = _upload_ImgDAL;
            project_Power_CutDAL = _project_Power_CutDAL;
            personDAL = _personDAL;
        }

        public async Task<Result> ImportWorker(Stream stream, string loginUserId, string departmentId, string projectId)
        {
            if (string.IsNullOrWhiteSpace(loginUserId))
            {
                return new Result("loginUserId不可为空");
            }
            if (string.IsNullOrWhiteSpace(departmentId))
            {
                return new Result("departmentId不可为空");
            }
            if (string.IsNullOrWhiteSpace(projectId))
            {
                return new Result("projectId不可为空");
            }
            List<Worker> list = new List<Worker>();
            try
            {
                Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(stream);
                Aspose.Cells.Worksheet sheet = wb.Worksheets[0];
                Aspose.Cells.Cells cells = sheet.Cells;
                if (cells.Rows.Count == 1)
                {
                    return new Result("导入数据至少一行");
                }
                for (int i = 1; i < cells.Rows.Count; i++)
                {
                    var row_cells = cells.Rows[i];
                    Worker worker = new Worker();
                    worker.Person_id = Guid.NewGuid().ToString("n");
                    worker.Createtime = DateTime.Now;

                    //项目id
                    worker.Project_id = projectId;

                    //工区id
                    worker.Department_id = departmentId;

                    //姓名
                    var xing_ming_cell = row_cells.GetCellOrNull(0);
                    worker.Real_name = xing_ming_cell.StringValue;

                    //工号
                    var gh_cell = row_cells.GetCellOrNull(1);
                    worker.Work_no = gh_cell.StringValue;

                    //本次岗位
                    var gw_cell = row_cells.GetCellOrNull(2);
                    worker.This_post = gw_cell.StringValue;

                    //职务
                    var zw_cell = row_cells.GetCellOrNull(3);
                    worker.Position = zw_cell.StringValue;

                    //安全等级(1到5级)
                    var aqdj_cell = row_cells.GetCellOrNull(4);
                    worker.Security_level = (byte)aqdj_cell.IntValue;

                    //技能等级
                    var jndj_cell = row_cells.GetCellOrNull(5);
                    worker.Skill_level = jndj_cell.StringValue;

                    //星级
                    var x_cell = row_cells.GetCellOrNull(6);
                    worker.Xing = (byte)x_cell.IntValue;

                    //作业内容
                    var zynr_cell = row_cells.GetCellOrNull(7);
                    worker.Work_content = zynr_cell.StringValue;

                    //携带设备
                    var dev_cell = row_cells.GetCellOrNull(8);
                    worker.Carry_equipment = dev_cell.StringValue;

                    list.Add(worker);
                }
            }
            catch (Exception ex)
            {
                var ep = ex.InnerException ?? ex;
                return new Result("读取EXCEL文件异常:" + ep.Message);
            }
            finally
            {
                stream?.Close();
                stream?.Dispose();
            }
            int count = await workerDAL.AddListAsync(list);
            if (count > 0)
            {
                //记录操作日志                
                Operate_log operate_Log = new Operate_log();
                operate_Log.Operate_user_id = loginUserId;
                operate_Log.Operate_type = 5;
                operate_Log.Operate_content = "项目批量导入工人";
                operate_Log.Old_data_id = projectId;
                operate_LogDAL.AddOperateLog(operate_Log);
                return new Result(true);
            }
            return new Result("导入工人失败");
        }

        /// 
        /// 保存用户导入的底图到项目信息
        /// 
        /// 图片id
        /// 项目id
        /// 当前登录用户id
        /// 
        /// 
        /// 创建时间:2021-9-14 11:19:36
        /// 
        public async Task<Result> SaveBackgroundImg(string imgId, string projectId, string loginUserId)
        {
            var find = await projectDAL.GetAsync(projectId);
            if (find == null)
            {
                return new Result("没有找到项目");
            }
            int count = await projectDAL.UpdateAsync(find, new string[] { "background_img_id" });
            if (count > 0)
            {
                //操作日志保存
                Operate_log operate_Log = new Operate_log();
                operate_Log.Operate_user_id = loginUserId;
                operate_Log.Operate_type = 4;
                operate_Log.Operate_content = "保存用户导入的底图到项目信息";
                operate_Log.Old_data_id = projectId;
                operate_LogDAL.AddOperateLog(operate_Log);
                return new Result(true);
            }
            return new Result("保存失败");
        }

        public async Task<Project> GetProject(string id)
        {
            return await projectDAL.GetAsync(id);
        }

        public async Task<PageModel<Project>> PageProject(Project project, int p, int rows)
        {
            Expression<Func<Project, bool>> expression = x => true;
            if (project != null)
            {
                //批准号
                if (!string.IsNullOrWhiteSpace(project.Approval_no))
                {
                    expression = expression.And(x => x.Approval_no.Contains(project.Approval_no));
                }

                //分工状态,0=待分工;1=已分工;2=已完成
                if (project.Division_stat.HasValue)
                {
                    expression = expression.And(x => x.Division_stat == project.Division_stat);
                }

                //开始日期
                if (project.Start_date.HasValue)
                {
                    var date = project.Start_date.Value.AddDays(-1);
                    expression = expression.And(x => x.Start_date > date);
                }

                //结束日期
                if (project.End_date.HasValue)
                {
                    var date = project.End_date.Value.AddDays(1);
                    expression = expression.And(x => x.Start_date < date);
                }

                //项目名称,
                if (string.IsNullOrWhiteSpace(project.Project_name))
                {
                    expression = expression.And(x => x.Project_name.Contains(project.Project_name));
                }
            }
            var page = await projectDAL.GetPageOrderByDescAsync(p, rows, expression, x => x.End_date);
            return page;
        }

        public async Task<Result> SaveListSafety_warningImg(List<Safety_warning> list, string loginUserId)
        {
            if (list == null || list.Count == 0)
            {
                return new Result("list不可为空");
            }
            foreach (var item in list)
            {
                item.Id = Guid.NewGuid().ToString("N");
                item.Create_time = DateTime.Now;
                if (string.IsNullOrWhiteSpace(item.Project_id))
                {
                    return new Result("Project_id不可为空");
                }
                if (string.IsNullOrWhiteSpace(item.Photo_id))
                {
                    return new Result("Photo_id不可为空");
                }
                if (string.IsNullOrWhiteSpace(item.Photo_url))
                {
                    return new Result("Photo_url不可为空");
                }
                item.Create_user_id = loginUserId;

                查询图片url
                //var imgInfo = await upload_ImgDAL.GetAsync(item.Photo_id);
                //item.Photo_url = imgInfo?.Url;

            }
            int count = await safety_WarningDAL.AddListAsync(list);
            if (count > 0)
            {
                return new Result(true);
            }
            return new Result("保存失败");
        }

        public async Task<Result> SaveListOverhaul(List<Overhaul> list, string loginUserId)
        {
            if (list == null || list.Count == 0)
            {
                return new Result("list不可为空");
            }
            foreach (var item in list)
            {
                item.Id = Guid.NewGuid().ToString("N");
                item.Create_time = DateTime.Now;
                if (string.IsNullOrWhiteSpace(item.Project_id))
                {
                    return new Result("Project_id不可为空");
                }
                if (string.IsNullOrWhiteSpace(item.Photo_id))
                {
                    return new Result("Photo_id不可为空");
                }
                if (string.IsNullOrWhiteSpace(item.Photo_url))
                {
                    return new Result("Photo_url不可为空");
                }
                item.Create_user_id = loginUserId;
            }
            int count = await overhaulDAL.AddListAsync(list);
            if (count > 0)
            {
                return new Result(true);
            }
            return new Result("保存失败");
        }

        public async Task<List<Overhaul>> GetOverhauls(string projectId)
        {
            return await overhaulDAL.GetListAsync(x => x.Project_id == projectId);
        }

        public async Task<List<Safety_warning>> GetListSafety_warningImg(string projectId)
        {
            return await safety_WarningDAL.GetListAsync(x => x.Project_id == projectId);
        }

        public async Task<Result> AddProject_power_cutAsync(Project_power_cut power_Cut)
        {
            if (power_Cut == null)
            {
                return new Result("power_Cut不可为空");
            }
            if (string.IsNullOrWhiteSpace(power_Cut.Photo_url))
            {
                return new Result("Photo_url不可为空");
            }
            if (string.IsNullOrWhiteSpace(power_Cut.Photo_id))
            {
                return new Result("Photo_id不可为空");
            }
            if (string.IsNullOrWhiteSpace(power_Cut.Project_id))
            {
                return new Result("Project_id不可为空");
            }

            //根据用户id查询姓名,WPF登录用户,当前操作人
            var person = await personDAL.GetAsync(power_Cut.Create_user_id);
            power_Cut.Create_real_name = person?.Real_name;

            power_Cut.Id = Guid.NewGuid().ToString("n");
            power_Cut.Createtime = DateTime.Now;
            int count = await project_Power_CutDAL.AddAsync(power_Cut);
            if (count > 0)
            {
                //记录操作日志
                Operate_log operate_Log = new Operate_log();
                operate_Log.Operate_user_id = person.Person_id;
                operate_Log.Operate_type = 11;
                operate_Log.User_type = 2;
                operate_Log.Operate_content = "新增停电范围上传的图片记录";
                operate_Log.New_data_id = power_Cut.Id;
                operate_LogDAL.AddOperateLog(operate_Log);
                return new Result(true);
            }
            return new Result("保存失败");
        }

        public async Task<Result> SaveProjectSelectedVideoList(List<Station_video> list)
        {
            if (list == null || list.Count > 0)
            {
                return new Result("list不可为空");
            }
            foreach (var item in list)
            {
                if (string.IsNullOrWhiteSpace(item.Project_id))
                {
                    return new Result("Project_id不可为空");
                }
                if (string.IsNullOrWhiteSpace(item.Upload_video_id))
                {
                    return new Result("Upload_video_id不可为空");
                }
                item.Station_video_id = Guid.NewGuid().ToString("n");
            }
            int count = await station_VideoDAL.AddListAsync(list);
            if (count > 0)
            {
                return new Result("保存成功");
            }
            return new Result("保存失败");
        }

    }
}

控制器调用:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.IBusiness;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong.Controllers
{
    /// 
    /// 项目相关,控制器
    /// 
    public class ProjectController : BaseController
    {
        readonly IProjectBusiness projectBusiness;
        readonly ITrainBusiness trainBusiness;
        readonly IGroundLineBusiness groundLineBusiness;


        public ProjectController(IProjectBusiness _projectBusiness
            , IGroundLineBusiness _groundLineBusiness
            , ITrainBusiness _trainBusiness)
        {
            projectBusiness = _projectBusiness;
            trainBusiness = _trainBusiness;
            groundLineBusiness = _groundLineBusiness;
        }

        //保存项目底图
        public async Task<IActionResult> SaveBackgroundImg(string imgId, string projectId, string loginUserId)
        {
            var result = await projectBusiness.SaveBackgroundImg(imgId, projectId, loginUserId);
            return Json(result);
        }
   }
}

Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.IDAL;

namespace WebMvcNetCore.TuShi.FenGong
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //  CreateHostBuilder(args).Build().Run();
            var build = CreateHostBuilder(args).Build();

            //执行更新项目到本系统
            Task.Run(() =>
            {
                try
                {
                    IProjectDAL projectDAL = (IProjectDAL)build.Services.GetService(typeof(IProjectDAL));
                    projectDAL.PullProjectList();
                    System.Threading.Thread.Sleep(3600 * 1000);
                }
                catch (Exception)
                {                     
                }     
            });

            build.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    .UseIIS();
                    //.UseHttpSys(o =>
                    //{
                    //    o.MaxRequestBodySize = null;
                    //});

                    //.UseKestrel(o =>
                    // {
                    //     o.Limits.MaxRequestBodySize = null;
                    //     o.Limits.MaxRequestBufferSize = null;
                    //     o.Limits.MaxRequestLineSize = 104857600;
                    // });
                });
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using WebMvcNetCore.TuShi.FenGong.BusinessImpl;
using WebMvcNetCore.TuShi.FenGong.DAL_Impl;
using WebMvcNetCore.TuShi.FenGong.IBusiness;
using WebMvcNetCore.TuShi.FenGong.IDAL;
using WebMvcNetCore.TuShi.FenGong.Model;

namespace WebMvcNetCore.TuShi.FenGong
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews()

               //自定义格式化json使用Newtonsoft.Json,安装Microsoft.AspNetCore.Mvc.NewtonsoftJson
               .AddNewtonsoftJson();

            services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(options =>
            {
                // Set the limit to 2560 MB
                //设置单位,字节
                options.MultipartBodyLengthLimit = 2680435456;
            });

            //services.Configure(x =>
            //{
            //    x.ValueLengthLimit = int.MaxValue;
            //    x.MultipartBodyLengthLimit = int.MaxValue;
            //    x.MultipartHeadersLengthLimit = int.MaxValue;
            //});

            //解决中文输出后被编码了
            services.Configure<Microsoft.Extensions.WebEncoders.WebEncoderOptions>(options =>
            {
                options.TextEncoderSettings = new System.Text.Encodings.Web.TextEncoderSettings(System.Text.Unicode.UnicodeRanges.All);
            });

            //会话存活时间,单位(秒)
            int sessionTime = 0;
            
            //读取配置文件
            int.TryParse(MyConfigReader.GetConfigValue("session_live_time"), out sessionTime);
            if (sessionTime == 0)
            {
                sessionTime = 7200;
            }
            services.AddSession(options =>
            {
                //设置cookie名称
                //options.Cookie.Name = ".AspNetCore.Session";
                //会话滑动过期时间,距下次访问最小时间,超过则session失效
                options.IdleTimeout = TimeSpan.FromSeconds(sessionTime);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });


            //services.AddScoped();
            //services.AddScoped();
            //services.AddScoped();            
            //services.AddScoped(); 
            //services.AddScoped(); 
            //services.AddScoped(); 
            //services.AddScoped();      

            //services.AddScoped();
            //services.AddScoped();
            //services.AddScoped();
            //services.AddScoped();
            //services.AddScoped();

            //业务层自动注册
            string path = AppDomain.CurrentDomain.BaseDirectory;
            Assembly bll_impl = Assembly.LoadFrom(path + "WebMvcNetCore.TuShi.FenGong.BusinessImpl.dll");
            Assembly bll_interface = Assembly.LoadFrom(path + "WebMvcNetCore.TuShi.FenGong.IBusiness.dll");
            var typesInterface = bll_interface.GetTypes();
            var typesImpl = bll_impl.GetTypes();
            foreach (var item in typesInterface)
            {
                var name = item.Name.Substring(1);
                string implBLLImpName = name + "Impl";
                var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));
                if (impl != null)
                {
                    services.AddSingleton(item, impl);
                }
            }

            //数据层自动注册 
            Assembly dalAssemblys = Assembly.LoadFrom(path + "WebMvcNetCore.TuShi.FenGong.DAL_Impl.dll");
            Assembly dalInterface = Assembly.LoadFrom(path + "WebMvcNetCore.TuShi.FenGong.IDAL.dll");
            var dalTypesImpl = dalAssemblys.GetTypes();
            var dalTypesInterface = dalInterface.GetTypes();
            foreach (var item in dalTypesInterface)
            {
                var name = item.Name.Substring(1);
                string implDalName = name + "Impl";
                var impl = dalTypesImpl.FirstOrDefault(w => w.Name.Equals(implDalName));
                if (impl != null)
                {
                    services.AddSingleton(item, impl);
                }
            }

            services.AddMvcCore();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();
            app.UseSession();

            app.Use(async (context, next) =>
            {
                if (context.Request.Method == "OPTIONS")
                {
                    //允许处理跨域
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                    context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
                    context.Response.Headers.Add("Access-Control-Allow-Methods", "*");
                    await context.Response.CompleteAsync();
                }
                else
                {
                    //允许处理跨域
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                    context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
                    context.Response.Headers.Add("Access-Control-Allow-Methods", "*");
                    await next();
                }
            });

            app.UseAuthorization();
            app.UseStaticFiles();

            //提供上传的文件访问支持
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
                    //Path.Combine(env.ContentRootPath, "upload")),
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload")),
                RequestPath = "/upload",
                ServeUnknownFileTypes=true
            });


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Main}/{id?}");
            });



        }
    }
}

你可能感兴趣的:(EF,Core,C#,c#,EF,Core仓储模式)