//TODO: Move this to Program.cs, only when app launches/re-launches public static async void UseEnsureMigrations(this IApplicationBuilder builder) { using var serviceScope = builder.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope(); var tenants = await serviceScope.ServiceProvider.GetService <ITenantProvider>().GetTenants(); if (tenants.Count == 0) { return; } IDesignTimeDbContextFactory <DbContext> dbContextFactory = (IDesignTimeDbContextFactory <DbContext>) serviceScope.ServiceProvider.GetService(typeof(IDesignTimeDbContextFactory <DbContext>)); var dummyDbContext = dbContextFactory.CreateDbContext(null); var dbUpdateExist = dummyDbContext.Database.GetPendingMigrations().Any(); if (dbUpdateExist) { foreach (var tenant in tenants) { var context = dbContextFactory.CreateDbContext(new string[] { tenant.Id.ToString(), tenant.ConnectionString }); if (context != null) { await context.Database.MigrateAsync(); } } PushLatestScriptToStorage(dummyDbContext.Database.GenerateCreateScript()); } }
public void InsertOutput(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); // Act InsertResult insertResult; using (var context = contextFactory.CreateDbContext(null)) { insertResult = builder .CreateCommand <TestEntity>() .Insert <UpsertParams>(p => new TestEntity { Name = p.Name, Version = p.Version }) .Output(e => new InsertResult { Id = e.Id, Version = e.Version }) .Log(context, output) .Create(context) .QueryFirst(context.Database, upsertParams); } // Assert Assert.NotNull(insertResult); Assert.Equal(upsertParams.Version, insertResult.Version); using (var context = contextFactory.CreateDbContext(null)) { var inserted = context.Entities.Single(e => e.Id == insertResult.Id); Assert.Equal(upsertParams.Name, inserted.Name); Assert.Equal(upsertParams.Version, inserted.Version); } }
public void DeleteById(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var entity = fixture.Create <TestEntity>(); using (var context = contextFactory.CreateDbContext(null)) { context.Entities.Add(entity); context.SaveChanges(); } // Act int deleteCount; using (var context = contextFactory.CreateDbContext(null)) { deleteCount = builder .CreateCommand <TestEntity>() .Delete <DeleteParams>((e, p) => e.Id == p.Id) .Log(context, output) .Create(context) .Execute(context.Database, new DeleteParams { Id = entity.Id }); } // Assert Assert.Equal(1, deleteCount); using (var context = contextFactory.CreateDbContext(null)) { var exists = context.Entities.Any(e => e.Name == entity.Name); Assert.False(exists); } }
public void Insert(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); // Act int insertCount; using (var context = contextFactory.CreateDbContext(null)) { output.WriteLine($"####### {context.Database.ProviderName}"); insertCount = builder .CreateCommand <TestEntity>() .Insert <UpsertParams>(p => new TestEntity { Name = p.Name, Version = p.Version }) .Log(context, output) .Create(context) .Execute(context.Database, upsertParams); } // Assert Assert.Equal(1, insertCount); using (var context = contextFactory.CreateDbContext(null)) { var exists = context.Entities.Any(e => e.Name == upsertParams.Name); Assert.True(exists); } }
public void AddOrganizationRole(string name) { using (LInstContext entities = _dbContextFactory.CreateDbContext(new string[] { })) { OrganizationRole newRole = new OrganizationRole { Name = name, Description = "" }; entities.OrganizationRoles.Add(newRole); foreach (Organization org in entities.Organizations) { OrganizationRoleMapping newMapping = new OrganizationRoleMapping { OrganizationRole = newRole, Organization = org, IsSelected = false }; entities.OrganizationRoleMappings.Add(newMapping); } entities.SaveChanges(); } }
private static User CreateUser() { using (var ctx = _factory.CreateDbContext(new string[0])) { Console.WriteLine("Username (must be an Email): "); string username; do { username = Console.ReadLine(); } while (!username.IsValidEmail()); Console.WriteLine("Password"); var password = Console.ReadLine(); var user = JwtAuthenticationService.CreateNewUser(username); JwtAuthenticationService.UpdatePassword(user, password); ctx.Users.Add(user); ctx.SaveChanges(); var person = new RealPerson { Firstname = "Mr.", Lastname = "Administrator", UserId = user.Id }; ctx.RealPeople.Add(person); ctx.SaveChanges(); return(user); } }
public void InsertOrUpdate_UpsertExistingOutput(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); int existingId; using (var context = contextFactory.CreateDbContext(null)) { var entity = new TestEntity { Name = upsertParams.Name, Version = upsertParams.Version, }; context.Entities.Add(entity); context.SaveChanges(); existingId = entity.Id; } // Act UpsertParams result; using (var context = contextFactory.CreateDbContext(null)) { result = builder .CreateCommand <TestEntity>() .Insert <UpsertParams>(p => new TestEntity { Name = p.Name, Version = p.Version }) .OrUpdate( e => new { e.Name }, (e, p) => new TestEntity { Version = e.Version + 1, } ) .Output(e => new UpsertParams { Id = e.Id, Version = e.Version, }) .Log(context, output) .Create(context) .QueryFirstOrDefault(context.Database, upsertParams); } // Assert Assert.NotNull(result); using (var context = contextFactory.CreateDbContext(null)) { var inserted = context.Entities.Single(e => e.Name == upsertParams.Name); Assert.Equal(existingId, inserted.Id); Assert.Equal(upsertParams.Version + 1, inserted.Version); Assert.Equal(inserted.Id, result.Id); Assert.Equal(inserted.Version, result.Version); } }
public virtual bool Add <TEntity>(TEntity item) where TEntity : class { try { using (var context = dbContextFactory.CreateDbContext(dummystringargs)) { context.Set <TEntity>().Add(item); context.Entry(item).State = EntityState.Added; context.SaveChanges(); } } catch (Exception ex) { while (ex != null) { //SystemContainer.Logger.Fatal(ex, "Add"); ex = ex.InnerException; } return(false); } return(true); }
private void UpdateRootEntityAndItsChildrenIfPossible() { object rootEntityToUpdate = entitiesLeftToUpdate.Peek(); using (DbContext context = contextFactory.CreateDbContext(new string[0])) { TraverseEntityGraphUpdatingWhenPossible(rootEntityToUpdate, context); context.SaveChanges(); } entitiesLeftToUpdate.Dequeue(); }
private void ValidateEntityDoesntExistInDataBase(Entity entity) { using (DbContext context = contextFactory.CreateDbContext(new string[0])) { Entity fromRepo = GetEntityFromRepo(context, entity); if (fromRepo != null) { throw new DataAccessException("Object already exists in database."); } } }
public void InsertOrUpdate_UpsertExistingWhere(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); int existingId; using (var context = contextFactory.CreateDbContext(null)) { var entity = new TestEntity { Name = upsertParams.Name, Version = upsertParams.Version, }; context.Entities.Add(entity); context.SaveChanges(); existingId = entity.Id; } // Act int rowCount; using (var context = contextFactory.CreateDbContext(null)) { rowCount = builder .CreateCommand <TestEntity>() .Insert <UpsertParams>(p => new TestEntity { Name = p.Name, Version = p.Version }) .OrUpdate( e => new { e.Name }, (e, p) => new TestEntity { Version = e.Version + 1, } ) .Where((e, p) => e.Version < 0) .Log(context, output) .Create(context) .Execute(context.Database, upsertParams); } // Assert Assert.Equal(0, rowCount); using (var context = contextFactory.CreateDbContext(null)) { var existing = context.Entities.Single(e => e.Id == existingId); Assert.Equal(upsertParams.Version, existing.Version); } }
public IEnumerable <Instrument> GetCalibrationCalendar() { // Returns a list of the instruments under control, ordered by due calibration date using (LInstContext entities = _dbContextFactory.CreateDbContext(new string[] { })) { return(entities.Instruments.Include(ins => ins.InstrumentType) .Include(ins => ins.UtilizationArea) .Include(ins => ins.CalibrationResponsible) .Where(ins => ins.IsUnderControl == true) .OrderBy(ins => ins.CalibrationDueDate) .ToList()); } }
public async Task <Either <ExceptionResponse, UpdateAnimalCommandResponse> > Handle(UpdateAnimalCommand request, CancellationToken cancellationToken) { var commandParams = request.AnimalPayload; DeviceAssignedToAnimal deviceDto; Data.Domains.Animal.Animal existingAnimal = null; using (var context = _animalContextFactory.CreateDbContext(new string[0])) { deviceDto = await GetDeviceByCompositeKey(context, commandParams.DeviceIdentifier) .Match(some => some, () => throw new InvalidOperationException("Device not found.")); existingAnimal = deviceDto.Animal; if (existingAnimal == null) { return(ExceptionResponse.With( ErrorMessage: $"animal/{request.AnimalPayload.DeviceCompositeKey}", HttpStatusCode: HttpStatusCode.NotFound)); } existingAnimal.LastModifiedRequestID = request.RequestId; await context.SaveChangesAsync(request.RequestId); } return(new UpdateAnimalCommandResponse(existingAnimal)); }
private IEnumerable <Encounter> GetFilteredEncounters(Func <EncounterEntity, bool> predicate) { using (Context context = contextFactory.CreateDbContext(new string[0])) { return(context.Encounters.Where(predicate).Select(mapEntity).ToList()); } }
public LInst.User CreateNewUser(Person personInstance, string userName, string password) { LInst.User output = new LInst.User(); output.FullName = ""; output.UserName = userName; output.HashedPassword = CalculateHash(password, userName); using (LInstContext context = _contextFactory.CreateDbContext(new string[] { })) { output.Person = context.People.First(per => per.ID == personInstance.ID); foreach (UserRole role in context.UserRoles) { UserRoleMapping tempMapping = new UserRoleMapping(); tempMapping.UserRole = role; tempMapping.IsSelected = false; output.RoleMappings.Add(tempMapping); } context.Users.Add(output); context.SaveChanges(); } return(output); }
public ProMassSpammerModel GetDbContext() { //args isn't actually used, so it's always null - ignore the warning var context = _modelFactory.CreateDbContext(null); return(context); }
// Load config data from EF DB. public override void Load() { var seedData = _pluginConfigurationSeedData.Data; if (_connectionString.IsNullOrEmpty() || _connectionString == "...") { Data = seedData.ToDictionary( item => item.Name, item => item.Value); } else { using (var dbContext = _dbContextFactory.CreateDbContext(new[] { _connectionString })) { dbContext.Database.Migrate(); Data = dbContext.PluginConfigurationValues .AsNoTracking() .ToDictionary(c => c.Name, c => c.Value); if (!Data.Any()) { Data = seedData.ToDictionary( item => item.Name, item => item.Value); } } } }
public void InsertOrUpdate_UpdateExistingWhereOutput(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); using (var context = contextFactory.CreateDbContext(null)) { context.Entities.Add(new TestEntity { Name = upsertParams.Name, Version = upsertParams.Version, }); context.SaveChanges(); } // Act IEnumerable <UpsertParams> results; using (var context = contextFactory.CreateDbContext(null)) { results = builder .CreateCommand <TestEntity>() .Update <UpsertParams>((e, p) => new TestEntity { Version = e.Version + 1, }) .Where((e, p) => e.Name == p.Name) .Output(e => new UpsertParams { Id = e.Id, Version = e.Version }) .Log(context, output) .Create(context) .Query(context.Database, upsertParams); } // Assert Assert.Single(results); using (var context = contextFactory.CreateDbContext(null)) { var inserted = context.Entities.Single(e => e.Name == upsertParams.Name); Assert.Equal(upsertParams.Version + 1, inserted.Version); var result = results.Single(); Assert.Equal(upsertParams.Version + 1, result.Version); } }
public UnitOfWork(IDesignTimeDbContextFactory <DatabaseContext> databaseContext) { _context = databaseContext.CreateDbContext(args: null); Posts = new PostRepository(_context); Categories = new CategoryRepository(_context); Accounts = new AccountRepository(_context); PostCategories = new PostCategoryRepository(_context); }
public async Task <Either <ExceptionResponse, GetAnimalByDeviceIdentifierQueryResponse> > Handle( GetAnimalByDeviceIdentifierQuery request, CancellationToken cancellationToken) { GetAnimalByDeviceIdentifierQueryResponse response; using (var context = _animalContextFactory.CreateDbContext(new string[0])) { IQueryable <Device> deviceQuery; if (!string.IsNullOrEmpty(request.NlisId)) { deviceQuery = context.Devices .Include(x => x.DeviceDefinition) .Include(x => x.DeviceAssignment).ThenInclude(p => p.Animal) .Where(da => da.NLISID == request.NlisId); } else { deviceQuery = context.Devices .Include(x => x.DeviceDefinition) .Include(x => x.DeviceAssignment).ThenInclude(p => p.Animal) .Where(da => da.RFID == request.RfId); } var entity = await deviceQuery.FirstOrDefaultAsync(); Data.Domains.Animal.Animal animal = null; if (entity != null && entity.DeviceAssignment.Any()) { animal = entity.DeviceAssignment.FirstOrDefault(devAssgn => devAssgn.ReplacementDate == null)?.Animal; } else { return(ExceptionResponse.With( ErrorMessage: $"Associated Animal's data is not found. AnimalId = {request.NlisId ?? request.RfId}", HttpStatusCode: HttpStatusCode.NotFound)); } var deviceAssignedToAnimal = new DeviceAssignedToAnimal { Species = entity.DeviceDefinition.SpeciesID, IsPostBreederDevice = entity.DeviceDefinition.IsPostBreederDevice, NLISID = entity.NLISID, RFID = entity.RFID, AssignedToPropertyIdentifierID = entity.AssignedToPropertyIdentifierID, AssignmentDate = entity.AssignmentDate, DeviceID = entity.DeviceID, ExcludedDate = entity.ExcludedDate, ExcludedReasonID = entity.ExcludedReasonID, IssueToPropertyIdentifierID = entity.IssueToPropertyIdentifierID, CreatedRequestID = entity.CreatedRequestID, LastModifiedRequestID = entity.LastModifiedRequestID }; response = new GetAnimalByDeviceIdentifierQueryResponse(deviceAssignedToAnimal); } return(response); }
private G GenericRetry <G>(Func <G> retryMethod) { G result = default(G); try { result = retryMethod(); } catch (DbUpdateException exp) { _keySet.Rotate(); string[] args = new string[] { _keySet.Active.Identifier, _keySet.Active.Token }; _activeContext = _contextFactory.CreateDbContext(args); result = GenericRetry(retryMethod); _keySet.Refresh(); } return(result); }
public async Task <OkObjectResult> Index() { Person[] allPeople = new Person[0]; using (PrioritizeMeDbContext context = _factory.CreateDbContext(new string[0])) { allPeople = await context.People.ToArrayAsync(); } return(Ok(allPeople)); }
public void InsertOrUpdate_UpdateExistingWhere(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); using (var context = contextFactory.CreateDbContext(null)) { context.Entities.Add(new TestEntity { Name = upsertParams.Name, Version = upsertParams.Version, }); context.SaveChanges(); } // Act int updateCount; using (var context = contextFactory.CreateDbContext(null)) { updateCount = builder .CreateCommand <TestEntity>() .Update <UpsertParams>((e, p) => new TestEntity { Version = e.Version + 1, }) .Where((e, p) => e.Name == p.Name) .Log(context, output) .Create(context) .Execute(context.Database, upsertParams); } // Assert Assert.Equal(1, updateCount); using (var context = contextFactory.CreateDbContext(null)) { var inserted = context.Entities.Single(e => e.Name == upsertParams.Name); Assert.Equal(upsertParams.Version + 1, inserted.Version); } }
public IActionResult Post([FromBody] string value) { if (value == ResetDataBaseConfirmationKey) { using (Context context = contextFactory.CreateDbContext(new string[0])) { context.DeleteDataBase(); } using (Context context = contextFactory.CreateDbContext(new string[0])) { context.Users.Add(InitialUser); context.SaveChanges(); } return(Ok()); } else { return(Unauthorized()); } }
public void InsertOrUpdate_UpdateWithNullable(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); using (var context = contextFactory.CreateDbContext(null)) { context.Entities.Add(new TestEntity { Name = upsertParams.Name, Version = upsertParams.Version, }); context.SaveChanges(); } upsertParams.NullableVersion = null; // Act int rowCount; using (var context = contextFactory.CreateDbContext(null)) { rowCount = builder .CreateCommand <TestEntity>() .Update <UpsertParams>((e, p) => new TestEntity { Version = 1, }) .Where((e, p) => e.Version == p.NullableVersion || p.NullableVersion == null) .Log(context, output) .Create(context) .Execute(context.Database, upsertParams); } // Assert Assert.NotEqual(0, rowCount); }
public void InsertOrUpdate_UpsertNew(IDesignTimeDbContextFactory <TestDbContext> contextFactory) { // Arrange var upsertParams = fixture.Create <UpsertParams>(); // Act int rowCount; using (var context = contextFactory.CreateDbContext(null)) { rowCount = builder .CreateCommand <TestEntity>() .Insert <UpsertParams>(p => new TestEntity { Name = p.Name, Version = p.Version }) .OrUpdate( e => new { e.Name }, (e, p) => new TestEntity { Version = e.Version + 1, } ) .Log(context, output) .Create(context) .Execute(context.Database, upsertParams); } // Assert Assert.Equal(1, rowCount); using (var context = contextFactory.CreateDbContext(null)) { var inserted = context.Entities.Single(e => e.Name == upsertParams.Name); Assert.Equal(upsertParams.Version, inserted.Version); } }
public async Task <Either <ExceptionResponse, CreateAnimalCommandResponse> > Handle(CreateAnimalCommand request, CancellationToken cancellationToken) { var commandParams = request.AnimalPayload; DeviceAssignedToAnimal deviceDto; Data.Domains.Animal.Animal animal = null; using (var context = _animalContextFactory.CreateDbContext(new string[0])) { deviceDto = await GetDeviceByCompositeKey(context, commandParams.DeviceIdentifier) .Match(some => some, () => new DeviceAssignedToAnimal()); // todo MF: needs to be refactored if (deviceDto.DeviceID == 0) { return(ExceptionResponse.With(ErrorMessage: "Device not found.", HttpStatusCode: HttpStatusCode.NotFound)); } if (deviceDto.IssueToPropertyIdentifierID > 0) { if (!deviceDto.AnimalAssignedToDevice) { animal = AssignNewAnimalToDevice(context, deviceDto, commandParams.CurrentPropertyIdentifierId, commandParams.TransactionDate, request.RequestId); await ApplyPropertyRules(context, animal, deviceDto.AssignedToPropertyIdentifierID, commandParams.TransactionDate, request.RequestId); await context.SaveChangesAsync(request.RequestId); } else { animal = deviceDto.Animal; return(new CreateAnimalCommandResponse(animal)); } } } return(new CreateAnimalCommandResponse(animal)); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app">Injected <see cref="IApplicationBuilder"/></param> /// <param name="env">Injected <see cref="IHostingEnvironment"/></param> /// <param name="contextFactory">The application <see cref="IDesignTimeDbContextFactory{TContext}"/></param> public void Configure( IApplicationBuilder app, IHostingEnvironment env, IDesignTimeDbContextFactory <PrioritizeMeDbContext> contextFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); // Automatically migrate the application to the latest using (PrioritizeMeDbContext migrationContext = contextFactory.CreateDbContext(new string[0])) { migrationContext.Database.Migrate(); } } app.UseCors(MyAllowSpecificOrigins); app.UseHttpsRedirection(); app.UseMvc(); app.UseSwagger(c => { c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value); }); app.UseSwaggerUI( c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); }); }
public KmStandViewRepository(IDesignTimeDbContextFactory <ReadModelDbContext> contextFactory) { _contextFactory = contextFactory; _context = contextFactory.CreateDbContext(Array.Empty <string>()); }
public RiversDataProcessor(IDesignTimeDbContextFactory <RiversECO.DataContext.DataContext> contextFactory) { _dataContext = contextFactory.CreateDbContext(new string[0]); }