public void Send(LogModel[] logs) { if (logs.Length == 1) { // Get DbContext that will be used as a UoW. DbContext dbContext = _dbContextProvider.GetDbContext(logs[0]) ?? throw new Exception("Context provider returned null DB context"); // Get entity that will persisted. Object entity = _dbEntityBuilder.BuildDbEntity(logs[0]) ?? throw new Exception("Entity builder returned null entity"); // Persist the entity. dbContext.Add(entity); dbContext.SaveChanges(); } else { var contexts = new DbContext[logs.Length]; for (int i = 0; i < logs.Length; i++) { DbContext dbContext = _dbContextProvider.GetDbContext(logs[i]) ?? throw new Exception("Context provider returned null DbContext"); dbContext.Add(_dbEntityBuilder.BuildDbEntity(logs[i]) ?? throw new Exception("Entity builder returned null entity")); contexts[i] = dbContext; } for (int i = 0; i < contexts.Length; i++) { contexts[i].SaveChanges(); } } }
public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { try { using (var uow = _unitOfWorkManager.Begin()) { // Switching to host is necessary for single tenant mode. using (_unitOfWorkManager.Current.SetTenantId(null)) { if (!await _dbContextProvider.GetDbContext().Database.CanConnectAsync(cancellationToken)) { return(HealthCheckResult.Unhealthy("YoyoCmsTemplateDbContext无法连接到数据库" )); } var user = await _dbContextProvider.GetDbContext().Users.AnyAsync(cancellationToken); uow.Complete(); if (user) { return(HealthCheckResult.Healthy("YoyoCmsTemplateDbContext已连接到数据库和检查用户是否添加")); } return(HealthCheckResult.Unhealthy("YoyoCmsTemplateDbContext连接到数据库,但没有用户。")); } } } catch (Exception e) { return(HealthCheckResult.Unhealthy(L("YoyoCmsTemplateDbContextCouldNotConnectToDatabase"), e)); } }
public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { try { using (var uow = _unitOfWorkManager.Begin()) { // Switching to host is necessary for single tenant mode. using (_unitOfWorkManager.Current.SetTenantId(null)) { if (!await _dbContextProvider.GetDbContext().Database.CanConnectAsync(cancellationToken)) { return(HealthCheckResult.Unhealthy( "PortalDbContext could not connect to database" )); } var user = await _dbContextProvider.GetDbContext().Users.AnyAsync(cancellationToken); uow.Complete(); if (user) { return(HealthCheckResult.Healthy("PortalDbContext connected to database and checked whether user added")); } return(HealthCheckResult.Unhealthy("PortalDbContext connected to database but there is no user.")); } } } catch (Exception e) { return(HealthCheckResult.Unhealthy("PortalDbContext could not connect to database.", e)); } }
/// <summary> /// 根据RoleId获取所有不属于此角色的用户 /// </summary> /// <param name="RoleId"></param> /// <returns></returns> public async Task <List <User> > GetExcludeUsersByRoleId(int RoleId) { string strQuerySql = "SELECT u.Id, u.Name, u.UserName FROM dbo.Users u LEFT JOIN dbo.UserRoles r ON r.UserId = u.Id WHERE ISNULL(r.RoleId, 0) <> @RoleId"; SqlParameter[] param = new SqlParameter[] { new SqlParameter("@RoleId", RoleId) }; return(await Task.Run(() => provider.GetDbContext().Set <User>().Select(q => new User { Id = q.Id, Name = q.Name, UserName = q.UserName }).FromSql(strQuerySql, param).ToList())); }
protected async Task BulkInsertAsync <T>(IEnumerable <T> entities) where T : BaseEntity { if (entities.Any()) { PrepareForInsert(entities); var dbContext = _dbContextProvider.GetDbContext(); await dbContext.BulkInsertAsync(entities); } }
public int Execute(string sql, int count = 0, params object[] parameters) { try { return(_dbContextProvider.GetDbContext().Database.ExecuteSqlCommand(sql, parameters)); } catch (Exception e) { if (count >= 5) { throw e; } return(Execute(sql, count + 1, parameters)); } }
/// <summary> /// Method for resetting password /// </summary> /// <param name="resetPasswordDto">ResetPassword DTO</param> /// <returns>bool</returns> public async Task <bool> ResetPasswordFromLink <T>(T resetPasswordDto) where T : class { var newPassword = (string)typeof(T).GetProperty("NewPassword").GetValue(resetPasswordDto); var passwordToken = (string)typeof(T).GetProperty("PasswordToken").GetValue(resetPasswordDto); if (!new Regex(AccountAppService.PasswordRegex).IsMatch(newPassword)) { throw new UserFriendlyException(AppConsts.InvalidPasswordMessage); } var cn = _context.GetDbContext(); var user = await cn.Users.FirstOrDefaultAsync(x => x.PasswordResetCode == passwordToken); if (user != null) { var reslut = await _userManager.ChangePasswordAsync(user, newPassword); if (reslut.Succeeded) { user.PasswordResetCode = Guid.NewGuid().ToString(); await _userManager.UpdateAsync(user); return(true); } } throw new UserFriendlyException(AppConsts.AuthenticationFailedMessage); }
public EFRepository(IDbContextProvider dbContextProvider) { _dbSet = dbContextProvider ?.GetDbContext() ?.Set <TEntity>() ?? throw new ArgumentNullException(); }
public bool Exist(string connectionString) { if (connectionString.IsNullOrEmpty()) { //单元测试下连接字符串为空 return(true); } try { using (var uow = _unitOfWorkManager.Begin()) { // 在单租户模式下切换到host using (_unitOfWorkManager.Current.SetTenantId(null)) { _dbContextProvider.GetDbContext().Database.OpenConnection(); uow.Complete(); } } } catch { return(false); } return(true); }
public bool Exist(string connectionString) { if (connectionString.IsNullOrEmpty()) { //connectionString is null for unit tests return(true); } try { using (var uow = _unitOfWorkManager.Begin()) { // Switching to host is necessary for single tenant mode. using (_unitOfWorkManager.Current.SetTenantId(null)) { _dbContextProvider.GetDbContext().Database.OpenConnection(); uow.Complete(); } } } catch { return(false); } return(true); }
/// <summary> /// 获取当前用户的所有权限 /// </summary> /// <param name="Id"></param> /// <returns></returns> public async Task <List <Menu> > GetUserPermissions(string strUserName) { //执行存储过程 string strSql = "EXEC [dbo].[SP_GetUserPermissions] @UserName"; SqlParameter[] param = new SqlParameter[] { new SqlParameter("@UserName", strUserName) }; return(await Task.Run(() => provider.GetDbContext().Set <Menu>().FromSql(strSql, param).ToList())); }
public bool Commit(bool autoRollback = false) { using (var transaction = _dbContextProvider.GetDbContext().Database.BeginTransaction()) { try { _dbContextProvider.GetDbContext().SaveChanges(); //如果未执行到Commit()就执行失败遇到异常了,EF Core会自动进行数据回滚(前提是使用Using) transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); return(false); } } return(true); }
public IReadOnlyList <T> GetFromEngin3 <T>(string sql, object parameters = null, CommandType?commandType = null) { var tempDbConn = _dbContextDemo.GetDbContext(); string tempConnStr = tempDbConn.Database.GetDbConnection().ConnectionString; using (var conn = new SqlConnection(tempConnStr)) { return(conn.Query <T>(sql, parameters).ToList()); } }
public EFQueryHandler( IDbContextProvider dbContextProvider, IMapper mapper) { _dbSet = dbContextProvider ?.GetDbContext() ?.Set <TEntity>() ?? throw new ArgumentNullException(); _mapper = mapper ?? throw new ArgumentNullException(); }
public async Task <Logging> AddAsync(Logging entity) { var model = _mapper.Map <Model.LogInfoModel>(entity); await _dbContextProvider.GetDbContext().AddAsync(model); return(_mapper.Map <Logging>(model)); }
/// <summary> /// 调用ADO.NET执行SQL语句查询泛型集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="database">数据库连接上下文</param> /// <param name="sql">SQL语句</param> /// <param name="parameters">SQL语句需要的参数</param> /// <returns></returns> public static List <T> FromSqlEt <T>(this IDbContextProvider <JPGZServiceMysqlDbContext> database, string sql, object parameters = null) { var result = new List <T>(); using (var command = database.GetDbContext().Database.GetDbConnection().CreateCommand()) { command.CommandText = sql; if (parameters != null) { var _parameters = parameters.ToSqlParamsArray(); command.Parameters.AddRange(_parameters); } database.GetDbContext().Database.OpenConnection(); using (var reader = command.ExecuteReader()) { var dt = new DataTable(); dt.Load(reader); result = dt.ToList <T>(); return(result); } } }
private static void InsertUser(IDbContextProvider <CustomSplittingProvider> provider, int id) { var context = provider.GetDbContext(TableSplitRule.Instance.GetTableIndex(id)); context.Add(new User { Id = $"Id_{id}", UserName = $"User_{id}", Details = new UserDetails { UserId = $"Id_{id}", Address = $"Address_{id}", Email = $"Email_{id}", }, }); context.SaveChanges(); }
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { try { using (var uow = _unitOfWorkManager.Begin()) { if (await _dbContextProvider.GetDbContext().Database.CanConnectAsync(cancellationToken)) { return HealthCheckResult.Healthy("HealthCheckExampleDbContext could connect to database"); } } return HealthCheckResult.Unhealthy("HealthCheckExampleDbContext could not connect to database"); } catch (Exception e) { return HealthCheckResult.Unhealthy("Error when trying to check HealthCheckExampleDbContext. ", e); } }
public void DoSomeStuff() { using (IUnitOfWorkCompleteHandle uow = _unitOfWorkManager.Begin()) { _personRepository.Insert(new Person("Oğuzhan")); _personRepository.Insert(new Person("Ekmek")); _animalRepository.Insert(new Animal("Kuş")); _animalRepository.Insert(new Animal("Kedi")); _animalDbContextProvider.GetDbContext().Animals.Add(new Animal("Kelebek")); _unitOfWorkManager.Current.SaveChanges(); Animal animal = _animalRepository.FirstOrDefault(x => x.Name == "Kuş"); Person person = _personDapperRepository.Get(1); Person anotherPerson = _personRepository.Nolocking(persons => persons.FirstOrDefault(x => x.Name == "Ekmek")); uow.Complete(); } }
public bool Exist(string connectionString) { if (connectionString.IsNullOrEmpty()) { //connectionString is null for unit tests return(true); } try { using (var uow = _unitOfWorkManager.Begin()) { _dbContextProvider.GetDbContext().Database.OpenConnection(); uow.Complete(); } } catch (Exception ex) { return(false); } return(true); }
public RepositoryBase(IDbContextProvider <TContext> _dbContextProvider) { dbContextProvider = _dbContextProvider; Context = dbContextProvider.GetDbContext(); //this.resilientTransaction = ServiceProviderResolver.ServiceProvider.GetService<IResilientTransaction<TContext>>(); }
/// <inheritdoc /> public UnitOfWork(IDbContextProvider dbContextProvider) : base() { _dbContext = dbContextProvider.GetDbContext(); }
public int Execute(string sql, params object[] parameters) { return(DbContextProvider.GetDbContext().Database.ExecuteSqlCommand(sql, parameters)); }
public void DoSomeStuff() { using (IUnitOfWorkCompleteHandle uow = _unitOfWorkManager.Begin()) { Logger.Debug("Uow Began!"); _personRepository.Insert(new Person("Oğuzhan")); _personRepository.Insert(new Person("Ekmek")); _animalRepository.Insert(new Animal("Kuş")); _animalRepository.Insert(new Animal("Kedi")); _animalDbContextProvider.GetDbContext().Animals.Add(new Animal("Kelebek")); _unitOfWorkManager.Current.SaveChanges(); Person personCache = _cacheManager.GetCache(DemoCacheName.Demo).Get("person", () => _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan")); Person person = _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan"); Animal animal = _animalRepository.FirstOrDefault(x => x.Name == "Kuş"); #region DAPPER var list = new List <string> { "elma", "armut" }; ExpressionStarter <Animal> predicate = PredicateBuilder.New <Animal>(); predicate.And(x => x.Name == "Kuş"); IEnumerable <Animal> birdsSet = _animalDapperRepository.GetSet(new { Name = "Kuş" }, 0, 10, "Id"); IEnumerable <Person> personFromDapper = _personDapperRepository.GetList(new { Name = "Oğuzhan" }); IEnumerable <Animal> birdsFromExpression = _animalDapperRepository.GetSet(predicate, 0, 10, "Id"); IEnumerable <Animal> birdsPagedFromExpression = _animalDapperRepository.GetListPaged(x => x.Name == "Kuş", 0, 10, "Name"); IEnumerable <Person> personFromDapperExpression = _personDapperRepository.GetList(x => x.Name.Contains("Oğuzhan")); int birdCount = _animalDapperRepository.Count(x => x.Name == "Kuş"); var personAnimal = _animalDapperRepository.Query <PersonAnimal>("select Name as PersonName,'Zürafa' as AnimalName from Person with(nolock) where name=@name", new { name = "Oğuzhan" }) .MapTo <List <PersonAnimalDto> >(); birdsFromExpression.ToList(); birdsPagedFromExpression.ToList(); birdsSet.ToList(); IEnumerable <Person> person2FromDapper = _personDapperRepository.Query("select * from Person with(nolock) where name =@name", new { name = "Oğuzhan" }); #endregion Person person2Cache = _cacheManager.GetCache(DemoCacheName.Demo).Get("person", () => _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan")); Person oguzhan = _personRepository.Nolocking(persons => persons.FirstOrDefault(x => x.Name == "Oğuzhan")); Person oguzhan2 = _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan"); uow.Complete(); _messageBus.Publish <IPersonAddedMessage>(new PersonAddedMessage { Name = "Oğuzhan", CorrelationId = NewId.NextGuid() }); _hangfireBackgroundJobManager.EnqueueAsync <SimpleBackgroundJob, SimpleBackgroundJobArgs>(new SimpleBackgroundJobArgs { Message = "Oğuzhan" }); Logger.Debug("Uow End!"); } }
public EfCoreRepositoryBase(IDbContextProvider <TDbContext> dbContextProvider) { DbContext = dbContextProvider.GetDbContext(); }
public ProfessorUniSubjectsRepository(IDbContextProvider <eMMADbContext> context) : base(context) { _context = context.GetDbContext(); }
public LaboratoryRepository(IDbContextProvider <eMMADbContext> context) : base(context) { _context = context.GetDbContext(); }
public AnswerRepository(IDbContextProvider <eMMADbContext> context) : base(context) { _context = context.GetDbContext(); }
public BaseApp(IDbContextProvider <TDbConext> _dbContextProvider) { dbconext = _dbContextProvider.GetDbContext(); dbContextProvider = _dbContextProvider; }
public void DoSomeStuff() { try { using (IUnitOfWorkCompleteHandle uow = _unitOfWorkManager.Begin()) { Logger.Debug("Uow Began!"); int persionId1 = _personRepository.InsertAndGetId(new Person("Oğuzhan")); _personRepository.Insert(new Person("Ekmek")); int animalId1 = _animalRepository.InsertAndGetId(new Animal("Kuş")); _animalRepository.Insert(new Animal("Kedi")); _animalDbContextProvider.GetDbContext().Animals.Add(new Animal("Kelebek")); _unitOfWorkManager.Current.SaveChanges(); Person personCache = _cacheManager.GetCache(DemoCacheName.Demo).Get("person", () => _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan")); Person person = _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan"); Animal animal = _animalRepository.FirstOrDefault(x => x.Name == "Kuş"); using (StoveSession.Use(266)) { _productDapperRepository.Insert(new Product("TShirt1")); int gomlekId = _productDapperRepository.InsertAndGetId(new Product("Gomlek1")); Product firstProduct = _productDapperRepository.FirstOrDefault(x => x.Name == "TShirt1"); IEnumerable <Product> products = _productDapperRepository.GetAll(); firstProduct.Name = "Something"; _productDapperRepository.Update(firstProduct); _mailDapperRepository.Insert(new Mail("New Product Added")); Guid mailId = _mailDapperRepository.InsertAndGetId(new Mail("Second Product Added")); IEnumerable <Mail> mails = _mailDapperRepository.GetAll(); Mail firstMail = mails.First(); firstMail.Subject = "Sorry wrong email!"; _mailDapperRepository.Update(firstMail); } Animal oneAnimal = _animalDapperRepository.Get(animalId1); Animal oneAnimalAsync = _animalDapperRepository.GetAsync(animalId1).Result; Person onePerson = _personDapperRepository.Get(persionId1); Person onePersonAsync = _personDapperRepository.GetAsync(persionId1).Result; IEnumerable <Animal> birdsSet = _animalDapperRepository.GetSet(x => x.Name == "Kuş", 0, 10, "Id"); using (_unitOfWorkManager.Current.DisableFilter(StoveDataFilters.SoftDelete)) { IEnumerable <Person> personFromDapperNotFiltered = _personDapperRepository.GetAll(x => x.Name == "Oğuzhan"); } IEnumerable <Person> personFromDapperFiltered = _personDapperRepository.GetAll(x => x.Name == "Oğuzhan"); IEnumerable <Animal> birdsFromExpression = _animalDapperRepository.GetSet(x => x.Name == "Kuş", 0, 10, "Id"); IEnumerable <Animal> birdsPagedFromExpression = _animalDapperRepository.GetAllPaged(x => x.Name == "Kuş", 0, 10, "Name"); IEnumerable <Person> personFromDapperExpression = _personDapperRepository.GetAll(x => x.Name.Contains("Oğuzhan")); int birdCount = _animalDapperRepository.Count(x => x.Name == "Kuş"); var personAnimal = _animalDapperRepository.Query <PersonAnimal>("select Name as PersonName,'Zürafa' as AnimalName from Persons with(nolock) where name=@name", new { name = "Oğuzhan" }) .MapTo <List <PersonAnimalDto> >(); birdsFromExpression.ToList(); birdsPagedFromExpression.ToList(); birdsSet.ToList(); IEnumerable <Person> person2FromDapper = _personDapperRepository.Query("select * from Persons with(nolock) where name =@name", new { name = "Oğuzhan" }); _personDapperRepository.Insert(new Person("oğuzhan2")); int id = _personDapperRepository.InsertAndGetId(new Person("oğuzhan3")); Person person3 = _personDapperRepository.Get(id); person3.Name = "oğuzhan4"; _personDapperRepository.Update(person3); _personDapperRepository.Delete(person3); Person person2Cache = _cacheManager.GetCache(DemoCacheName.Demo).Get("person", () => _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan")); //Person oguzhan = _personRepository.Nolocking(persons => persons.FirstOrDefault(x => x.Name == "Oğuzhan")); Person oguzhan2 = _personRepository.FirstOrDefault(x => x.Name == "Oğuzhan"); uow.Complete(); _messageBus.Publish <IPersonAddedMessage>(new PersonAddedMessage { Name = "Oğuzhan", CorrelationId = NewId.NextGuid() }); //_hangfireBackgroundJobManager.EnqueueAsync<SimpleBackgroundJob, SimpleBackgroundJobArgs>(new SimpleBackgroundJobArgs //{ // Message = "Oğuzhan" //}); //_hangfireScheduleJobManager.ScheduleAsync<SimpleBackgroundJob, SimpleBackgroundJobArgs>(new SimpleBackgroundJobArgs //{ // Message = "Oğuzhan" //}, Cron.Minutely()); Logger.Debug("Uow End!"); } } catch (Exception ex) { Logger.Error(ex); throw ex; } }