Jack.EntityFrameworkCore 1.0.0.6

dotnet add package Jack.EntityFrameworkCore --version 1.0.0.6
                    
NuGet\Install-Package Jack.EntityFrameworkCore -Version 1.0.0.6
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Jack.EntityFrameworkCore" Version="1.0.0.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jack.EntityFrameworkCore" Version="1.0.0.6" />
                    
Directory.Packages.props
<PackageReference Include="Jack.EntityFrameworkCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Jack.EntityFrameworkCore --version 1.0.0.6
                    
#r "nuget: Jack.EntityFrameworkCore, 1.0.0.6"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Jack.EntityFrameworkCore@1.0.0.6
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Jack.EntityFrameworkCore&version=1.0.0.6
                    
Install as a Cake Addin
#tool nuget:?package=Jack.EntityFrameworkCore&version=1.0.0.6
                    
Install as a Cake Tool
docker pull mysql:5.7
docker volume create --name=mysqldata
docker run -d --name mysql_jack --restart=always -v mysqldata:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=change_me -p 3306:3306 -p 33060:33060 --security-opt=seccomp:unconfined --privileged mysql:5.7 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --innodb-rollback-on-timeout=ON
CREATE DATABASE `demo_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

CREATE TABLE `user` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `UserName` varchar(255) DEFAULT NULL,
  `Age` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户';
[Table("user")]
public class UserModel : BaseModel<int>
{
	public string UserName { get; set; }
	public int Age { get; set; }
}

public class DemoDbContext : JackDbContext<DemoDbContext>
{
	public DemoDbContext()
	{
	}

	public DemoDbContext(DbContextOptions<DemoDbContext> options) : base(options)
	{
	}
}
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.AddJackDbContext<Entities.DemoDbContext>(options =>
		{
			string connStr = "server=127.0.0.1;Database=demo_db;Uid=root;Pwd=change_me;Port=3306;Allow User Variables=True;SslMode=None;CharSet=UTF8;";
			options.UseMySql(connStr, ServerVersion.AutoDetect(connStr), mySqlOptions =>
			{
				mySqlOptions.CommandTimeout(3);
				mySqlOptions.MaxBatchSize(50);
			});
		}, new JackDbContextOptions { AddDefaultLogger = true, AddDefaultRepository = true });

		services.AddSwaggerGen(setup =>
		{
			OpenApiInfo info = new OpenApiInfo
			{
				Title = "{标题}",
				Version = "v1",
				Description = "描述",
				TermsOfService = new Uri(Assembly.GetEntryAssembly()!.ManifestModule.Name.Replace(".dll", ""), UriKind.Relative)
			};

			setup.SwaggerDoc(info.Version, info);

			string[] files = Directory.GetFiles(AppContext.BaseDirectory, "*.xml");
			string[] array = files;
			foreach (string filePath in array)
			{
				setup.IncludeXmlComments(filePath, includeControllerXmlComments: true);
			}
		});

		services.AddControllers().AddControllersAsServices();
	}

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		MySqlConnectorLogManager.Provider = new MicrosoftExtensionsLoggingLoggerProvider(app.ApplicationServices.GetRequiredService<ILoggerFactory>(), true);

		if (env.IsDevelopment())
		{
			app.UseSwagger();
			app.UseSwaggerUI(delegate (SwaggerUIOptions c)
			{
				c.SwaggerEndpoint("/swagger/v1/swagger.yaml", "{标题} API V1");
			});

			app.UseDeveloperExceptionPage();
		}

		app.UseRouting();

		app.UseAuthorization();

		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllers();
		});
	}
}
[Route("api/[controller]/[action]")]
[ApiController]
public class UserModelController : ControllerBase
{
	public UserModelController(IRepository<UserModel> userRepository, IUnitOfWork unitOfWork)
	{
		UserRepository = userRepository;
		UnitOfWork = unitOfWork;
	}

	public IRepository<UserModel> UserRepository { get; set; }
	public IUnitOfWork UnitOfWork { get; set; }

	[HttpPost]
	public async Task<ActionResult<UserModel>> RandomAddUserForRepository()
	{
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};
		await UserRepository.Insert(userModel);
		await UnitOfWork.SaveChanges();

		return userModel;
	}

	[HttpPost]
	public async Task<ActionResult<UserModel>> RandomAddUserForDapper()
	{
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};

		UnitOfWork.Open();
		userModel.Id = await UnitOfWork.ExecuteScalarAsync<int>("INSERT INTO `user` (UserName, Age) VALUES (@UserName, @Age); SELECT LAST_INSERT_ID();", userModel);
		UnitOfWork.Close();

		return userModel;
	}

	[HttpGet]
	public async Task<ActionResult<IPagedList<UserModel>>> GetPagedListForRepository([Required, Range(1, 1000)] int page = 1, [Required, Range(1, 100)] int pageSize = 10)
	{
		var pagedList = await UserRepository.Where(x => x.Id > 0).OrderByDescending(x => x.Age).ToPagedListAsync(page, pageSize);
		return Ok(pagedList);
	}

	[HttpGet]
	public async Task<ActionResult<IEnumerable<UserModel>>> GetPagedListForDapper([Required, Range(1, 1000)] int page = 1, [Required, Range(1, 100)] int pageSize = 10)
	{
		int skip = (page - 1) * pageSize;
		int take = pageSize;
		//using SqlClientListener sqlClientListener = new SqlClientListener();
		UnitOfWork.Open();
		var pagedList = await UnitOfWork.QueryAsync<UserModel>("SELECT * FROM `user` WHERE Id > 0 ORDER BY Age DESC LIMIT @skip, @take", new { skip, take });
		UnitOfWork.Close();

		return Ok(pagedList);
	}

	[HttpGet]
	public async Task UpdateSample([FromServices] IDbConnectionFactory<Entities.DemoDbContext> dbConnectionFactory, [FromServices] Entities.DemoDbContext demoDbContext)
	{
		var user = await UserRepository.FirstOrDefaultAsync(x => x.Id == 1);
		user.UserName = Guid.NewGuid().ToString();

		using var dbConn = dbConnectionFactory.CreateConnection(demoDbContext);
		dbConn.Open();
		await dbConn.ExecuteAsync("UPDATE `user` SET UserName = @UserName WHERE Id = @Id", user);
		dbConn.Close();
	}

	[HttpGet]
	public async Task UpdatePartialSample()
	{
		var users = await UserRepository.Take(5).ToListAsync();
		var random = new Random(Environment.TickCount);
		foreach (var user in users)
		{
			user.Age = random.Next(1, 120);
			user.UserName = Guid.NewGuid().ToString();
			UserRepository.UpdatePartial(user, "Age");
		}
		await UnitOfWork.SaveChanges();
	}

	[HttpGet]
	public async Task UpdateBatchSample()
	{
		var users = await UserRepository.Take(5).ToListAsync();
		var random = new Random(Environment.TickCount);
		foreach (var user in users)
		{
			user.Age = random.Next(1, 120);
			user.UserName = Guid.NewGuid().ToString();
		}

		UserRepository.UpdateMany(users);
		await UnitOfWork.SaveChanges();
	}

	[HttpGet]
	public async Task AddBatchSample()
	{
		List<UserModel> userModels = new List<UserModel>();
		for (int i = 0; i < 5; i++)
		{
			UserModel userModel = new UserModel
			{
				UserName = Guid.NewGuid().ToString(),
				Age = new Random(Environment.TickCount).Next(1, 120),
			};
			userModels.Add(userModel);
		}

		await UserRepository.InsertMany(userModels);
		await UnitOfWork.SaveChanges();
	}

	[HttpGet]
	public async Task DeleteBatchByIdsSample()
	{
		var userIds = await UserRepository.Select(x => x.Id).Take(5).ToArrayAsync();
		UserRepository.Delete(userIds);
		await UnitOfWork.SaveChanges();
	}

	#region Transaction Scope
	[HttpGet]
	public async Task<UserModel> TransactionScopeSample()
	{
		UnitOfWork.OpenTransactionScope();
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};
		await UserRepository.Insert(userModel);
		await UnitOfWork.SaveChanges();

		return userModel;
	}

	[HttpGet]
	public async Task<UserModel> TransactionScopeSample2()
	{
		UnitOfWork.OpenTransactionScope();
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};

		try
		{
			await UserRepository.Insert(userModel);
			await UnitOfWork.SaveChanges();

			if (userModel.Id > 0)
			{
				throw new InvalidOperationException("异常测试");
			}
		}
		catch (Exception)
		{
			UnitOfWork.SetTransactionScopeFailed();
			throw;
		}

		return userModel;
	}

	[HttpGet]
	public async Task<UserModel> TransactionScopeSample3()
	{
		UnitOfWork.OpenTransactionScope();
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};

		await UnitOfWork.TransactionDecorator(async trans =>
		{
			await UserRepository.Insert(userModel);
			await UnitOfWork.SaveChanges();
		});

		await UnitOfWork.TransactionDecorator(async trans =>
		{
			await UserRepository.Insert(userModel);
			await UnitOfWork.SaveChanges();
		});

		return userModel;
	}

	[HttpGet]
	public async Task<UserModel> TransactionScopeSample4()
	{
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};

		await UnitOfWork.TransactionDecorator(async trans =>
		{
			await UserRepository.Insert(userModel);
			await UnitOfWork.SaveChanges();
		});

		await UnitOfWork.TransactionDecorator(async trans =>
		{
			UnitOfWork.TryOpen();
			userModel.Id = await UnitOfWork.ExecuteScalarAsync<int>("INSERT INTO `user` (Id, UserName, Age) VALUES (@Id, @UserName, @Age); SELECT LAST_INSERT_ID();", userModel, trans);
		});

		return userModel;
	}

	[HttpGet]
	public async Task<UserModel> TransactionScopeSample5()
	{
		UserModel userModel = new UserModel
		{
			UserName = Guid.NewGuid().ToString(),
			Age = new Random(Environment.TickCount).Next(1, 120),
		};

		await UnitOfWork.TransactionDecorator(async trans =>
		{
			UnitOfWork.TryOpen();
			userModel.Id = await UnitOfWork.ExecuteScalarAsync<int>("INSERT INTO `user` (Id, UserName, Age) VALUES (@Id, @UserName, @Age); SELECT LAST_INSERT_ID();", userModel, trans);
		});

		await UnitOfWork.TransactionDecorator(async trans =>
		{
			await UserRepository.Insert(userModel);
			await UnitOfWork.SaveChanges();
		});

		return userModel;
	}
	#endregion
}
public IUnitOfWork UnitOfWork { get; set; }
public IEfCoreUnitOfWork<DemoDbContext> EfCoreUnitOfWork { get; set; }

[HttpGet]
public void Get()
{
	var userRepository = UnitOfWork.CreateRepository<UserModel>();
	var userRepository2 = UnitOfWork.CreateRepository<UserModel>();
	var userEfCoreRepository = EfCoreUnitOfWork.CreateEfCoreRepository<UserModel>();

	Console.WriteLine(UnitOfWork == EfCoreUnitOfWork);
	Console.WriteLine(Object.ReferenceEquals(UnitOfWork, EfCoreUnitOfWork));

	Console.WriteLine(userRepository == userEfCoreRepository);
	Console.WriteLine(Object.ReferenceEquals(userRepository, userEfCoreRepository));

	Console.WriteLine(userRepository == userRepository2);
	Console.WriteLine(Object.ReferenceEquals(userRepository, userRepository2));
}

[HttpGet]
public void Get2()
{
	EfCoreUnitOfWork<DemoDbContext> efCoreUnitOfWork1 = UnitOfWork as EfCoreUnitOfWork<DemoDbContext>;
	EfCoreUnitOfWork<DemoDbContext> efCoreUnitOfWork2 = EfCoreUnitOfWork as EfCoreUnitOfWork<DemoDbContext>;

	Console.WriteLine(efCoreUnitOfWork1.DbContext == efCoreUnitOfWork2.DbContext);
	Console.WriteLine(Object.ReferenceEquals(efCoreUnitOfWork1.DbContext, efCoreUnitOfWork2.DbContext));
}

[HttpGet]
public void Get3()
{
	IScopeService scopeService = EfCoreUnitOfWork.DbContext.GetService<IScopeService>();
	IScopeService scopeService1 = EfCoreUnitOfWork.DbContext.GetService<IScopeService>();
	IServiceProvider serviceProvider = EfCoreUnitOfWork.DbContext.GetInfrastructure<IServiceProvider>();

	Console.WriteLine(scopeService == scopeService1);
	Console.WriteLine(Object.ReferenceEquals(scopeService, scopeService1));
}
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.