├── EF_DbHelper ├── Extension │ ├── packages.config │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── QueryableExtension.cs │ └── Extension.csproj ├── Model │ ├── packages.config │ ├── AccoutInfo.cs │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Model.csproj ├── Test │ ├── packages.config │ ├── Program.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── App.config │ └── Test.csproj ├── DbHelp │ ├── packages.config │ ├── Strategy │ │ ├── IReadDbStrategy.cs │ │ ├── SingleStrategy.cs │ │ └── RandomStrategy.cs │ ├── ModelConfigurations │ │ └── AccountInfoConfiguration.cs │ ├── DBContext │ │ ├── WriteDbContext.cs │ │ ├── BaseReadDbContext.cs │ │ ├── ReadDbContainer.cs │ │ └── DBContextFactory.cs │ ├── App.config │ ├── Migrations │ │ └── Configuration.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── DbHelp.csproj │ └── Base │ │ └── DbBase.cs └── EF_DbHelper.sln ├── README.md └── .gitignore /EF_DbHelper/Extension/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /EF_DbHelper/Model/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /EF_DbHelper/Test/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /EF_DbHelper/Model/AccoutInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Model 4 | { 5 | public class AccoutInfo 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | public DateTime? Time { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/Strategy/IReadDbStrategy.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace DbHelp.Strategy 4 | { 5 | /// 6 | /// 从数据库获取策略接口 7 | /// 8 | public interface IReadDbStrategy 9 | { 10 | /// 11 | /// 获取读库 12 | /// 13 | /// 14 | DbContext GetDbContext(); 15 | } 16 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/Strategy/SingleStrategy.cs: -------------------------------------------------------------------------------- 1 | using DbHelp.DBContext; 2 | using System.Data.Entity; 3 | 4 | namespace DbHelp.Strategy 5 | { 6 | /// 7 | /// 单一策略 8 | /// 9 | public class SingleStrategy : IReadDbStrategy 10 | { 11 | public DbContext GetDbContext() 12 | { 13 | return new ReadDbContext(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/ModelConfigurations/AccountInfoConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Model; 2 | using System.Data.Entity.ModelConfiguration; 3 | 4 | namespace DbHelp.ModelConfigurations 5 | { 6 | public class AccoutInfoConfiguration : EntityTypeConfiguration 7 | { 8 | public AccoutInfoConfiguration() 9 | { 10 | HasKey(o => o.Id); 11 | Property(o => o.Name).IsRequired(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/DBContext/WriteDbContext.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | using System.Reflection; 3 | 4 | namespace DbHelp.DBContext 5 | { 6 | public class WriteDbContext : DbContext 7 | { 8 | public WriteDbContext() : 9 | base("name=connWriteStr") 10 | { 11 | Configuration.AutoDetectChangesEnabled = true; 12 | } 13 | 14 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 15 | { 16 | modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); 17 | base.OnModelCreating(modelBuilder); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EF_DbHelper 2 | **Entity Framework 数据访问通用类,支持读写分离** 3 | 4 | - DbBase.cs 为通用操作封装类 5 | - DBContextFactory.cs 为获取DBContext的工厂模型 6 | - 如果需要实现自己的切换策略,可自己继承IReadDbStrategy后,自己写扩展 7 | 8 | --- 9 | 10 | **使用例子如下:** 11 | 12 | DbBase db = new DbBase(); 13 | var model = new AccoutInfo() 14 | { 15 | Name = "qt", 16 | Time = DateTime.Now 17 | }; 18 | db.Insert(model); 19 | db.SaveChanges(); 20 | 21 | Thread.Sleep(3000); 22 | 23 | var account = db.FirstOrDefault(p => p.Id == model.Id); 24 | Console.WriteLine(account.Name); 25 | -------------------------------------------------------------------------------- /EF_DbHelper/Test/Program.cs: -------------------------------------------------------------------------------- 1 | using DbHelp.Base; 2 | using Model; 3 | using System; 4 | using System.Threading; 5 | 6 | namespace Test 7 | { 8 | internal class Program 9 | { 10 | private static void Main(string[] args) 11 | { 12 | //todo:这里仅仅是测试DbBase类的使用,实际使用可以自己结合项目做分层使用 13 | 14 | DbBase db = new DbBase(); 15 | var model = new AccoutInfo() 16 | { 17 | Name = "qt", 18 | Time = DateTime.Now 19 | }; 20 | db.Insert(model); 21 | db.SaveChanges(); 22 | 23 | Thread.Sleep(3000); 24 | 25 | var account = db.FirstOrDefault(p => p.Id == model.Id); 26 | Console.WriteLine(account.Name); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /EF_DbHelper/Model/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/DBContext/BaseReadDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using System.Reflection; 4 | 5 | namespace DbHelp.DBContext 6 | { 7 | public class BaseReadDbContext : DbContext 8 | { 9 | static BaseReadDbContext() 10 | { 11 | Database.SetInitializer(new NullDatabaseInitializer()); 12 | } 13 | 14 | public BaseReadDbContext(string connReadStr) : base(connReadStr) 15 | { 16 | Configuration.AutoDetectChangesEnabled = false; 17 | } 18 | 19 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 20 | { 21 | modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); 22 | base.OnModelCreating(modelBuilder); 23 | } 24 | 25 | public override int SaveChanges() 26 | { 27 | throw new InvalidOperationException("只读数据库,不允许写入"); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/Migrations/Configuration.cs: -------------------------------------------------------------------------------- 1 | namespace DbHelp.Migrations 2 | { 3 | using System.Data.Entity.Migrations; 4 | 5 | internal sealed class Configuration : DbMigrationsConfiguration 6 | { 7 | public Configuration() 8 | { 9 | AutomaticMigrationsEnabled = true; 10 | } 11 | 12 | protected override void Seed(DbHelp.DBContext.WriteDbContext context) 13 | { 14 | // This method will be called after migrating to the latest version. 15 | 16 | // You can use the DbSet.AddOrUpdate() helper extension method 17 | // to avoid creating duplicate seed data. E.g. 18 | // 19 | // context.People.AddOrUpdate( 20 | // p => p.FullName, 21 | // new Person { FullName = "Andrew Peters" }, 22 | // new Person { FullName = "Brice Lambson" }, 23 | // new Person { FullName = "Rowan Miller" } 24 | // ); 25 | // 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /EF_DbHelper/Model/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | [assembly: AssemblyTitle("Model")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("Microsoft")] 11 | [assembly: AssemblyProduct("Model")] 12 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | //将 ComVisible 设置为 false 将使此程序集中的类型 17 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 18 | //请将此类型的 ComVisible 特性设置为 true。 19 | [assembly: ComVisible(false)] 20 | 21 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 22 | [assembly: Guid("6cf97a39-dac5-4a59-820a-f89ecec6e017")] 23 | 24 | // 程序集的版本信息由下列四个值组成: 25 | // 26 | // 主版本 27 | // 次版本 28 | // 生成号 29 | // 修订号 30 | // 31 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 32 | // 方法是按如下所示使用“*”: : 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /EF_DbHelper/Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | [assembly: AssemblyTitle("Test")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("Microsoft")] 11 | [assembly: AssemblyProduct("Test")] 12 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | //将 ComVisible 设置为 false 将使此程序集中的类型 17 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 18 | //请将此类型的 ComVisible 特性设置为 true。 19 | [assembly: ComVisible(false)] 20 | 21 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 22 | [assembly: Guid("2741082b-6132-431d-8410-fe3a6d2bfb3b")] 23 | 24 | // 程序集的版本信息由下列四个值组成: 25 | // 26 | // 主版本 27 | // 次版本 28 | // 生成号 29 | // 修订号 30 | // 31 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 32 | // 方法是按如下所示使用“*”: : 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/DBContext/ReadDbContainer.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace DbHelp.DBContext 4 | { 5 | public class ReadDbContext : BaseReadDbContext 6 | { 7 | static ReadDbContext() 8 | { 9 | Database.SetInitializer(new NullDatabaseInitializer()); 10 | } 11 | 12 | public ReadDbContext() : base("connReadStr") 13 | { 14 | } 15 | } 16 | 17 | public class ReadDb1Context : BaseReadDbContext 18 | { 19 | static ReadDb1Context() 20 | { 21 | Database.SetInitializer(new NullDatabaseInitializer()); 22 | } 23 | 24 | public ReadDb1Context() : base("connReadStr1") 25 | { 26 | } 27 | } 28 | 29 | public class ReadDb2Context : BaseReadDbContext 30 | { 31 | static ReadDb2Context() 32 | { 33 | Database.SetInitializer(new NullDatabaseInitializer()); 34 | } 35 | 36 | public ReadDb2Context() : base("connReadStr2") 37 | { 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | [assembly: AssemblyTitle("DbHelp")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("Microsoft")] 11 | [assembly: AssemblyProduct("DbHelp")] 12 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | //将 ComVisible 设置为 false 将使此程序集中的类型 17 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 18 | //请将此类型的 ComVisible 特性设置为 true。 19 | [assembly: ComVisible(false)] 20 | 21 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 22 | [assembly: Guid("a9e92503-01d5-4e97-a649-52be695688b1")] 23 | 24 | // 程序集的版本信息由下列四个值组成: 25 | // 26 | // 主版本 27 | // 次版本 28 | // 生成号 29 | // 修订号 30 | // 31 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 32 | // 方法是按如下所示使用“*”: : 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /EF_DbHelper/Extension/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 5 | // 控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | [assembly: AssemblyTitle("Extension")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("Microsoft")] 11 | [assembly: AssemblyProduct("Extension")] 12 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | //将 ComVisible 设置为 false 将使此程序集中的类型 17 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 18 | //请将此类型的 ComVisible 特性设置为 true。 19 | [assembly: ComVisible(false)] 20 | 21 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 22 | [assembly: Guid("7a2844a5-26ef-40c4-a895-5418f9f7e382")] 23 | 24 | // 程序集的版本信息由下列四个值组成: 25 | // 26 | // 主版本 27 | // 次版本 28 | // 生成号 29 | // 修订号 30 | // 31 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 32 | // 方法是按如下所示使用“*”: : 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /EF_DbHelper/Extension/QueryableExtension.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper.QueryableExtensions; 2 | using System; 3 | using System.Linq; 4 | 5 | namespace Extension 6 | { 7 | public static class QueryableExtension 8 | { 9 | /// 10 | /// 分页查询扩展 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | public static IQueryable PageBy(this IQueryable query, int skipCount, int maxResultCount) 18 | { 19 | if (query == null) 20 | throw new ArgumentNullException(nameof(query)); 21 | return query.Skip(skipCount).Take(maxResultCount); 22 | } 23 | 24 | /// 25 | /// 查询扩展 26 | /// 27 | /// 28 | /// 29 | /// 30 | public static IQueryable Select(this IQueryable query) 31 | { 32 | if (query == null) 33 | throw new ArgumentNullException(nameof(query)); 34 | return query.ProjectTo(); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/DBContext/DBContextFactory.cs: -------------------------------------------------------------------------------- 1 | using DbHelp.Strategy; 2 | using System.Data.Entity; 3 | using System.Runtime.Remoting.Messaging; 4 | 5 | namespace DbHelp.DBContext 6 | { 7 | public class DbContextFactory 8 | { 9 | //todo:这里可以自己通过注入的方式来实现,就会更加灵活 10 | private static readonly IReadDbStrategy ReadDbStrategy = new RandomStrategy(); 11 | 12 | public DbContext GetWriteDbContext() 13 | { 14 | string key = typeof(DbContextFactory).Name + "WriteDbContext"; 15 | DbContext dbContext = CallContext.GetData(key) as DbContext; 16 | if (dbContext == null) 17 | { 18 | dbContext = new WriteDbContext(); 19 | CallContext.SetData(key, dbContext); 20 | } 21 | return dbContext; 22 | } 23 | 24 | public DbContext GetReadDbContext() 25 | { 26 | string key = typeof(DbContextFactory).Name + "ReadDbContext"; 27 | DbContext dbContext = CallContext.GetData(key) as DbContext; 28 | if (dbContext == null) 29 | { 30 | dbContext = ReadDbStrategy.GetDbContext(); 31 | CallContext.SetData(key, dbContext); 32 | } 33 | return dbContext; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/Strategy/RandomStrategy.cs: -------------------------------------------------------------------------------- 1 | using DbHelp.DBContext; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Data.Entity; 5 | using System.Reflection; 6 | 7 | namespace DbHelp.Strategy 8 | { 9 | /// 10 | /// 随机策略 11 | /// 12 | public class RandomStrategy : IReadDbStrategy 13 | { 14 | //所有读库类型 15 | public static List DbTypes; 16 | 17 | static RandomStrategy() 18 | { 19 | LoadDbs(); 20 | } 21 | 22 | //加载所有的读库类型 23 | private static void LoadDbs() 24 | { 25 | DbTypes = new List(); 26 | var assembly = Assembly.GetExecutingAssembly(); 27 | var types = assembly.GetTypes(); 28 | foreach (var type in types) 29 | { 30 | if (type.BaseType == typeof(BaseReadDbContext)) 31 | { 32 | DbTypes.Add(type); 33 | } 34 | } 35 | } 36 | 37 | public DbContext GetDbContext() 38 | { 39 | int randomIndex = new Random().Next(0, DbTypes.Count); 40 | var dbType = DbTypes[randomIndex]; 41 | var dbContext = Activator.CreateInstance(dbType) as DbContext; 42 | return dbContext; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /EF_DbHelper/Test/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /EF_DbHelper/EF_DbHelper.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbHelp", "DbHelp\DbHelp.csproj", "{A9E92503-01D5-4E97-A649-52BE695688B1}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Model\Model.csproj", "{6CF97A39-DAC5-4A59-820A-F89ECEC6E017}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Extension", "Extension\Extension.csproj", "{7A2844A5-26EF-40C4-A895-5418F9F7E382}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{2741082B-6132-431D-8410-FE3A6D2BFB3B}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {A9E92503-01D5-4E97-A649-52BE695688B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {A9E92503-01D5-4E97-A649-52BE695688B1}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {A9E92503-01D5-4E97-A649-52BE695688B1}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {A9E92503-01D5-4E97-A649-52BE695688B1}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {6CF97A39-DAC5-4A59-820A-F89ECEC6E017}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {6CF97A39-DAC5-4A59-820A-F89ECEC6E017}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {6CF97A39-DAC5-4A59-820A-F89ECEC6E017}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {6CF97A39-DAC5-4A59-820A-F89ECEC6E017}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {7A2844A5-26EF-40C4-A895-5418F9F7E382}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {7A2844A5-26EF-40C4-A895-5418F9F7E382}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {7A2844A5-26EF-40C4-A895-5418F9F7E382}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {7A2844A5-26EF-40C4-A895-5418F9F7E382}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {2741082B-6132-431D-8410-FE3A6D2BFB3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {2741082B-6132-431D-8410-FE3A6D2BFB3B}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {2741082B-6132-431D-8410-FE3A6D2BFB3B}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {2741082B-6132-431D-8410-FE3A6D2BFB3B}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | EndGlobal 41 | -------------------------------------------------------------------------------- /EF_DbHelper/Extension/Extension.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7A2844A5-26EF-40C4-A895-5418F9F7E382} 8 | Library 9 | Properties 10 | Extension 11 | Extension 12 | v4.5.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 35 | True 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 61 | -------------------------------------------------------------------------------- /EF_DbHelper/Model/Model.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {6CF97A39-DAC5-4A59-820A-F89ECEC6E017} 8 | Library 9 | Properties 10 | Model 11 | Model 12 | v4.5.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 39 | True 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 67 | -------------------------------------------------------------------------------- /EF_DbHelper/Test/Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {2741082B-6132-431D-8410-FE3A6D2BFB3B} 8 | Exe 9 | Properties 10 | Test 11 | Test 12 | v4.5.1 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 38 | True 39 | 40 | 41 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 42 | True 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | {a9e92503-01d5-4e97-a649-52be695688b1} 65 | DbHelp 66 | 67 | 68 | {6cf97a39-dac5-4a59-820a-f89ecec6e017} 69 | Model 70 | 71 | 72 | 73 | 80 | -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/DbHelp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A9E92503-01D5-4E97-A649-52BE695688B1} 8 | Library 9 | Properties 10 | DbHelp 11 | DbHelp 12 | v4.5.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\AutoMapper.5.2.0\lib\net45\AutoMapper.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 39 | True 40 | 41 | 42 | ..\packages\EntityFramework.Extended.6.1.0.168\lib\net45\EntityFramework.Extended.dll 43 | True 44 | 45 | 46 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 47 | True 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | {7a2844a5-26ef-40c4-a895-5418f9f7e382} 79 | Extension 80 | 81 | 82 | {6cf97a39-dac5-4a59-820a-f89ecec6e017} 83 | Model 84 | 85 | 86 | 87 | 88 | 95 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /EF_DbHelper/DbHelp/Base/DbBase.cs: -------------------------------------------------------------------------------- 1 | using DbHelp.DBContext; 2 | using EntityFramework.Extensions; 3 | using Extension; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data; 7 | using System.Data.Entity; 8 | using System.Data.Entity.Infrastructure; 9 | using System.Data.SqlClient; 10 | using System.Linq; 11 | using System.Linq.Dynamic; 12 | using System.Linq.Expressions; 13 | using System.Reflection; 14 | using System.Text; 15 | 16 | namespace DbHelp.Base 17 | { 18 | public class DbBase 19 | { 20 | //是否读写分离(可以配置在配置文件中) 21 | private static readonly bool IsReadWriteSeparation = true; 22 | 23 | #region EF上下文对象(主库) 24 | 25 | protected DbContext MasterDb => _masterDb.Value; 26 | private readonly Lazy _masterDb = new Lazy(() => new DbContextFactory().GetWriteDbContext()); 27 | 28 | #endregion EF上下文对象(主库) 29 | 30 | #region EF上下文对象(从库) 31 | 32 | protected DbContext SlaveDb => IsReadWriteSeparation ? _slaveDb.Value : _masterDb.Value; 33 | private readonly Lazy _slaveDb = new Lazy(() => new DbContextFactory().GetReadDbContext()); 34 | 35 | #endregion EF上下文对象(从库) 36 | 37 | #region 自定义其他方法 38 | 39 | /// 40 | /// 执行存储过程或自定义sql语句--返回集合(自定义返回类型) 41 | /// 42 | /// 43 | /// 44 | /// 45 | /// 46 | public List Query(string sql, List parms, CommandType cmdType = CommandType.Text) 47 | { 48 | //存储过程(exec getActionUrlId @name,@ID) 49 | if (cmdType == CommandType.StoredProcedure) 50 | { 51 | StringBuilder paraNames = new StringBuilder(); 52 | foreach (var sqlPara in parms) 53 | { 54 | paraNames.Append($" @{sqlPara},"); 55 | } 56 | sql = paraNames.Length > 0 ? $"exec {sql} {paraNames.ToString().Trim(',')}" : $"exec {sql} "; 57 | } 58 | var list = SlaveDb.Database.SqlQuery(sql, parms.ToArray()); 59 | var enityList = list.ToList(); 60 | return enityList; 61 | } 62 | 63 | /// 64 | /// 自定义语句和存储过程的增删改--返回影响的行数 65 | /// 66 | /// 67 | /// 68 | /// 69 | /// 70 | public int Execute(string sql, List parms, CommandType cmdType = CommandType.Text) 71 | { 72 | //存储过程(exec getActionUrlId @name,@ID) 73 | if (cmdType == CommandType.StoredProcedure) 74 | { 75 | StringBuilder paraNames = new StringBuilder(); 76 | foreach (var sqlPara in parms) 77 | { 78 | paraNames.Append($" @{sqlPara},"); 79 | } 80 | sql = paraNames.Length > 0 ? 81 | $"exec {sql} {paraNames.ToString().Trim(',')}" : 82 | $"exec {sql} "; 83 | } 84 | int ret = MasterDb.Database.ExecuteSqlCommand(sql, parms.ToArray()); 85 | return ret; 86 | } 87 | 88 | #endregion 自定义其他方法 89 | } 90 | 91 | /// 92 | /// mssql数据库 数据层 父类 93 | /// 94 | /// 95 | public class DbBase : DbBase where T : class, new() 96 | { 97 | #region INSERT 98 | 99 | /// 100 | /// 新增 实体 101 | /// 102 | /// 103 | /// 104 | public void Insert(T model) 105 | { 106 | MasterDb.Set().Add(model); 107 | } 108 | 109 | /// 110 | /// 普通批量插入 111 | /// 112 | /// 113 | public void InsertRange(List datas) 114 | { 115 | MasterDb.Set().AddRange(datas); 116 | } 117 | 118 | #endregion INSERT 119 | 120 | #region DELETE 121 | 122 | /// 123 | /// 根据模型删除 124 | /// 125 | /// 包含要删除id的对象 126 | /// 127 | public void Delete(T model) 128 | { 129 | MasterDb.Set().Attach(model); 130 | MasterDb.Set().Remove(model); 131 | } 132 | 133 | /// 134 | /// 删除 135 | /// 136 | /// 137 | public void Delete(Expression> whereLambda) 138 | { 139 | MasterDb.Set().Where(whereLambda).Delete(); 140 | } 141 | 142 | #endregion DELETE 143 | 144 | #region UPDATE 145 | 146 | /// 147 | /// 单个对象指定列修改 148 | /// 149 | /// 要修改的实体对象 150 | /// 要修改的 属性 名称 151 | /// 152 | /// 153 | public void Update(T model, List proNames, bool isProUpdate = true) 154 | { 155 | //将 对象 添加到 EF中 156 | MasterDb.Set().Attach(model); 157 | var setEntry = ((IObjectContextAdapter)MasterDb).ObjectContext.ObjectStateManager.GetObjectStateEntry(model); 158 | //指定列修改 159 | if (isProUpdate) 160 | { 161 | foreach (string proName in proNames) 162 | { 163 | setEntry.SetModifiedProperty(proName); 164 | } 165 | } 166 | //忽略类修改 167 | else 168 | { 169 | Type t = typeof(T); 170 | List proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); 171 | foreach (var item in proInfos) 172 | { 173 | string proName = item.Name; 174 | if (proNames.Contains(proName)) 175 | { 176 | continue; 177 | } 178 | setEntry.SetModifiedProperty(proName); 179 | } 180 | } 181 | } 182 | 183 | /// 184 | /// 单个对象修改 185 | /// 186 | /// 187 | /// 188 | public void Update(T model) 189 | { 190 | DbEntityEntry entry = MasterDb.Entry(model); 191 | MasterDb.Set().Attach(model); 192 | entry.State = EntityState.Modified; 193 | } 194 | 195 | /// 196 | /// 批量修改 197 | /// 198 | /// 199 | /// 200 | public void Update(Expression> whereLambda, Expression> updateExpression) 201 | { 202 | MasterDb.Set().Where(whereLambda).Update(updateExpression); 203 | } 204 | 205 | /// 206 | /// 批量修改 207 | /// 208 | /// 209 | /// 210 | public void UpdateAll(List models) 211 | { 212 | foreach (var model in models) 213 | { 214 | DbEntityEntry entry = MasterDb.Entry(model); 215 | entry.State = EntityState.Modified; 216 | } 217 | } 218 | 219 | /// 220 | /// 批量统一修改 221 | /// 222 | /// 要修改的实体对象 223 | /// 查询条件 224 | /// 225 | /// 226 | public void Update(T model, Expression> whereLambda, params string[] modifiedProNames) 227 | { 228 | //查询要修改的数据 229 | List listModifing = MasterDb.Set().Where(whereLambda).ToList(); 230 | Type t = typeof(T); 231 | List proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); 232 | Dictionary dictPros = new Dictionary(); 233 | proInfos.ForEach(p => 234 | { 235 | if (modifiedProNames.Contains(p.Name)) 236 | { 237 | dictPros.Add(p.Name, p); 238 | } 239 | }); 240 | if (dictPros.Count <= 0) 241 | { 242 | throw new Exception("指定修改的字段名称有误或为空"); 243 | } 244 | foreach (var item in dictPros) 245 | { 246 | PropertyInfo proInfo = item.Value; 247 | 248 | //取出 要修改的值 249 | object newValue = proInfo.GetValue(model, null); 250 | 251 | //批量设置 要修改 对象的 属性 252 | foreach (T oModel in listModifing) 253 | { 254 | //为 要修改的对象 的 要修改的属性 设置新的值 255 | proInfo.SetValue(oModel, newValue, null); 256 | } 257 | } 258 | } 259 | 260 | #endregion UPDATE 261 | 262 | #region SELECT 263 | 264 | /// 265 | /// 根据主键查询 266 | /// 267 | /// 268 | /// 269 | public T FindById(dynamic id) 270 | { 271 | return SlaveDb.Set().Find(id); 272 | } 273 | 274 | /// 275 | /// 获取默认一条数据,没有则为NULL 276 | /// 277 | /// 278 | /// 279 | public T FirstOrDefault(Expression> whereLambda = null) 280 | { 281 | if (whereLambda == null) 282 | { 283 | return SlaveDb.Set().FirstOrDefault(); 284 | } 285 | return SlaveDb.Set().FirstOrDefault(whereLambda); 286 | } 287 | 288 | /// 289 | /// 获取全部数据 290 | /// 291 | /// 292 | public List GetAll(string ordering = null) 293 | { 294 | return ordering == null 295 | ? SlaveDb.Set().ToList() 296 | : SlaveDb.Set().OrderBy(ordering).ToList(); 297 | } 298 | 299 | /// 300 | /// 带条件查询获取数据 301 | /// 302 | /// 303 | /// 304 | /// 305 | public List GetAll(Expression> whereLambda, string ordering = null) 306 | { 307 | var iQueryable = SlaveDb.Set().Where(whereLambda); 308 | return ordering == null 309 | ? iQueryable.ToList() 310 | : iQueryable.OrderBy(ordering).ToList(); 311 | } 312 | 313 | /// 314 | /// 带条件查询获取数据 315 | /// 316 | /// 317 | /// 318 | public IQueryable GetAllIQueryable(Expression> whereLambda = null) 319 | { 320 | return whereLambda == null ? SlaveDb.Set() : SlaveDb.Set().Where(whereLambda); 321 | } 322 | 323 | /// 324 | /// 获取数量 325 | /// 326 | /// 327 | /// 328 | public int GetCount(Expression> whereLambd = null) 329 | { 330 | return whereLambd == null ? SlaveDb.Set().Count() : SlaveDb.Set().Where(whereLambd).Count(); 331 | } 332 | 333 | /// 334 | /// 判断对象是否存在 335 | /// 336 | /// 337 | /// 338 | public bool Any(Expression> whereLambd) 339 | { 340 | return SlaveDb.Set().Where(whereLambd).Any(); 341 | } 342 | 343 | /// 344 | /// 分页查询 345 | /// 346 | /// 当前页码 347 | /// 每页大小 348 | /// 总条数 349 | /// 排序条件(一定要有) 350 | /// 查询添加(可有,可无) 351 | /// 是否是Order排序 352 | /// 353 | public List Page(int pageIndex, int pageSize, out int rows, Expression> orderBy, Expression> whereLambda = null, bool isOrder = true) 354 | { 355 | IQueryable data = isOrder ? 356 | SlaveDb.Set().OrderBy(orderBy) : 357 | SlaveDb.Set().OrderByDescending(orderBy); 358 | 359 | if (whereLambda != null) 360 | { 361 | data = data.Where(whereLambda); 362 | } 363 | rows = data.Count(); 364 | return data.PageBy((pageIndex - 1) * pageSize, pageSize).ToList(); 365 | } 366 | 367 | /// 368 | /// 分页查询 369 | /// 370 | /// 当前页码 371 | /// 每页大小 372 | /// 总条数 373 | /// 排序条件(一定要有) 374 | /// 查询添加(可有,可无) 375 | /// 376 | public List Page(int pageIndex, int pageSize, out int rows, string ordering, Expression> whereLambda = null) 377 | { 378 | // 分页 一定注意: Skip 之前一定要 OrderBy 379 | var data = SlaveDb.Set().OrderBy(ordering); 380 | if (whereLambda != null) 381 | { 382 | data = data.Where(whereLambda); 383 | } 384 | rows = data.Count(); 385 | return data.PageBy((pageIndex - 1) * pageSize, pageSize).ToList(); 386 | } 387 | 388 | /// 389 | /// 查询转换 390 | /// 391 | /// 392 | /// 393 | /// 394 | public List Select(Expression> whereLambda) 395 | { 396 | return SlaveDb.Set().Where(whereLambda).Select().ToList(); 397 | } 398 | 399 | #endregion SELECT 400 | 401 | #region ORTHER 402 | 403 | /// 404 | /// 执行存储过程或自定义sql语句--返回集合 405 | /// 406 | /// 407 | /// 408 | /// 409 | /// 410 | public List Query(string sql, List parms, CommandType cmdType = CommandType.Text) 411 | { 412 | return Query(sql, parms, cmdType); 413 | } 414 | 415 | /// 416 | /// 提交保存 417 | /// 418 | /// 419 | public int SaveChanges() 420 | { 421 | return MasterDb.SaveChanges(); 422 | } 423 | 424 | /// 425 | /// 回滚 426 | /// 427 | public void RollBackChanges() 428 | { 429 | var items = MasterDb.ChangeTracker.Entries().ToList(); 430 | items.ForEach(o => o.State = EntityState.Unchanged); 431 | } 432 | 433 | #endregion ORTHER 434 | } 435 | } --------------------------------------------------------------------------------