/// <summary> /// Create a new game /// </summary> /// <param name="playerName"></param> /// <param name="numberOfPlayers"></param> /// <returns>Game info</returns> public Game Create(string playerName, int numberOfPlayers) { using (IDbContextScope contextScope = _dbContextFactory.Create()) { //create player var player = new Player() { Name = playerName }; //create game var game = new Game() { NumberOfPlayers = numberOfPlayers, Status = numberOfPlayers > 1 ? 0 : 1 }; //add player to game game.Players.Add(player); //add game and player to database _gameService.Add(game); contextScope.SaveChanges(); game.PlayerId = player.Id; return(game); } }
public WynnDbContextScope( IDbContextScope dbContextScope, IAmbientDbContextLocator dbContextLocator) { _dbContextScope = dbContextScope; _dbContextLocator = dbContextLocator; }
public void UpdateCreditScoreForAllUsers() { /* * Demo of DbContextScope + parallel programming. */ using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create()) { //-- Get all users UserManagementDbContext dbContext = dbContextScope.DbContexts.Get <UserManagementDbContext>(); List <Guid> userIds = dbContext.Users.Select(u => u.Id).ToList(); Console.WriteLine("Found {0} users in the database. Will calculate and store their credit scores in parallel.", userIds.Count); //-- Calculate and store the credit score of each user // We're going to imagine that calculating a credit score of a user takes some time. // So we'll do it in parallel. // You MUST call SuppressAmbientContext() when kicking off a parallel execution flow // within a DbContextScope. Otherwise, this DbContextScope will remain the ambient scope // in the parallel flows of execution, potentially leading to multiple threads // accessing the same DbContext instance. using (_dbContextScopeFactory.SuppressAmbientContext()) { Parallel.ForEach(userIds, UpdateCreditScore); } // Note: SaveChanges() isn't going to do anything in this instance since all the changes // were actually made and saved in separate DbContextScopes created in separate threads. dbContextScope.SaveChanges(); } }
public void SendWelcomeEmail(Guid userId) { /* * Demo of forcing the creation of a new DbContextScope * to ensure that changes made to the model in this service * method are persisted even if that method happens to get * called within the scope of a wider business transaction * that eventually fails for any reason. * * This is an advanced feature that should be used as rarely * as possible (and ideally, never). */ // We're going to send a welcome email to the provided user // (if one hasn't been sent already). Once sent, we'll update // that User entity in our DB to record that its Welcome email // has been sent. // Emails can't be rolled-back. Once they're sent, they're sent. // So once the email has been sent successfully, we absolutely // must persist this fact in our DB. Even if that method is called // by another busines logic service method as part of a wider // business transaction and even if that parent business transaction // ends up failing for any reason, we still must ensure that // we have recorded the fact that the Welcome email has been sent. // Otherwise, we would risk spamming our users with repeated Welcome // emails. // Force the creation of a new DbContextScope so that the changes we make here are // guaranteed to get persisted regardless of what happens after this method has completed. using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create(DbContextScopeOption.ForceCreateNew)) { UserManagementDbContext dbContext = dbContextScope.DbContexts.Get <UserManagementDbContext>(); #if EF6 User user = dbContext.Users.Find(userId); #elif EFCore var user = dbContext.Users.SingleOrDefault(x => x.Id == userId); #endif if (user == null) { throw new ArgumentException($"Invalid userId provided: {userId}. Couldn't find a User with this ID."); } if (!user.WelcomeEmailSent) { SendEmail(user.Email); user.WelcomeEmailSent = true; } dbContextScope.SaveChanges(); // When you force the creation of a new DbContextScope, you must force the parent // scope (if any) to reload the entities you've modified here. Otherwise, the method calling // you might not be able to see the changes you made here. dbContextScope.RefreshEntitiesInParentScope(new List <User> { user }); } }
/// <summary> /// Creates the specified storage. /// </summary> /// <param name="storage">The instance of <see cref="Storage" /> type to create.</param> /// <returns>The newly created instance of <see cref="Storage" /> type.</returns> public async Task <Storage> CreateStorage(Storage storage) { StorageContract storageContract = await this.mapper.MapNewAsync <Storage, StorageContract>(storage); CatalogContract catalogContract = await this.mapper.MapNewAsync <Storage, CatalogContract>(storage); using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); catalogContract = await catalogRepository.SaveAsync(catalogContract); storageContract.ID = catalogContract.ID; IStorageRepository storageRepository = scope.GetRepository <IStorageRepository>(); storageContract = await storageRepository.SaveAsync(storageContract); scope.Commit(); } storage = await this.mapper.MapAsync(storageContract, storage); storage = await this.mapper.MapAsync(catalogContract, storage); return(storage); }
/// <summary> /// Creates the specified catalog entry. /// </summary> /// <param name="stream">The stream of <see cref="CatalogEntryStream" /> type to create the entry from.</param> /// <returns>The newly created instance of <see cref="CatalogEntry" /> type.</returns> public async Task <CatalogEntry> CreateCatalogEntry(CatalogEntryStream stream) { CatalogEntry entry = stream.Entry; FileContract fileContract = await this.mapper.MapNewAsync <CatalogEntry, FileContract>(entry); CatalogContract catalogContract = null; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { IFileRepository fileRepository = scope.GetRepository <IFileRepository>(); fileContract = await fileRepository.SaveAsync(fileContract); ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); catalogContract = await catalogRepository.GetAsync(fileContract.DirectoryID); scope.Commit(); } entry = await this.mapper.MapAsync(fileContract, entry); entry.Catalog = await this.mapper.MapAsync(catalogContract, entry.Catalog); return(entry); }
public void CreateUser(UserCreationSpec userToCreate) { if (userToCreate == null) { throw new ArgumentNullException(nameof(userToCreate)); } userToCreate.Validate(); /* * Typical usage of DbContextScope for a read-write business transaction. * It's as simple as it looks. */ using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create()) { //-- Build domain model User user = new User() { Id = userToCreate.Id, Name = userToCreate.Name, Email = userToCreate.Email, WelcomeEmailSent = false, CreatedOn = DateTime.UtcNow }; //-- Persist _userRepository.Add(user); dbContextScope.SaveChanges(); } }
public void CreateListOfUsersWithIntentionalFailure(params UserCreationSpec[] usersToCreate) { /* * Here, we'll verify that inner DbContextScopes really join the parent scope and * don't persist their changes until the parent scope completes successfully. */ bool firstUser = true; using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create()) { foreach (UserCreationSpec toCreate in usersToCreate) { if (firstUser) { CreateUser(toCreate); Console.WriteLine("Successfully created a new User named '{0}'.", toCreate.Name); firstUser = false; } else { // OK. So we've successfully persisted one user. // We're going to simulate a failure when attempting to // persist the second user and see what ends up getting // persisted in the DB. throw new Exception($"Oh no! An error occurred when attempting to create user named '{toCreate.Name}' in our database."); } } dbContextScope.SaveChanges(); } }
/// <summary> /// Updates the specified catalog. /// </summary> /// <param name="catalog">The instance of <see cref="Catalog" /> type to update.</param> /// <returns>The updated instance of <see cref="Catalog"/> type.</returns> public async Task <Catalog> UpdateCatalog(Catalog catalog) { CatalogContract catalogContract = null; CatalogContract parentCatalogContract = null; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); catalogContract = await catalogRepository.GetAsync(catalog.ID); catalogContract = await this.mapper.MapAsync(catalog, catalogContract); if (catalogContract.IsChanged) { catalogContract = await catalogRepository.SaveAsync(catalogContract); } if ((catalogContract?.ParentID).HasValue) { parentCatalogContract = await catalogRepository.GetAsync(catalogContract.ParentID.Value); } scope.Commit(); } catalog = await this.mapper.MapAsync(catalogContract, catalog); catalog.Parent = await this.mapper.MapAsync(parentCatalogContract, catalog.Parent); return(catalog); }
/// <summary> /// Updates the specified storage. /// </summary> /// <param name="storage">The instance of <see cref="Storage" /> type to update.</param> /// <returns>The updated instance of <see cref="Storage"/> type.</returns> public async Task <Storage> UpdateStorage(Storage storage) { StorageContract storageContract = null; CatalogContract catalogContract = null; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { IStorageRepository storageRepository = scope.GetRepository <IStorageRepository>(); storageContract = await storageRepository.GetAsync(storage.ID); storageContract = await this.mapper.MapAsync(storage, storageContract); if (storageContract.IsChanged) { storageContract = await storageRepository.SaveAsync(storageContract); } ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); catalogContract = await catalogRepository.GetAsync(storage.ID); scope.Commit(); } storage = await this.mapper.MapAsync(storageContract, storage); storage = await this.mapper.MapAsync(catalogContract, storage); return(storage); }
private static async Task <Box> GetSenderBox(CreateTk103Gps message, IDbContextScope dbContextScopeFactory) { var dbContext = dbContextScopeFactory.DbContexts.Get <SmartFleetObjectContext>(); var box = await dbContext.Boxes.Include(x => x.Vehicle).Include(x => x.Vehicle.Customer).FirstOrDefaultAsync(b => b.SerialNumber == message.SerialNumber); return(box); }
private static async Task <Box> GetSenderBox(string imei, IDbContextScope dbContextScopeFactory) { var dbContext = dbContextScopeFactory.DbContexts.Get <SmartFleetObjectContext>(); var box = await dbContext.Boxes.Include(x => x.Vehicle).Include(x => x.Vehicle.Customer).FirstOrDefaultAsync(b => b.Imei == imei); return(box); }
public static int ExecuteCommand( this IDbContextScope ctx, string query, params object[] Parametros ) { return(ctx.DbContexts.Get <ApplicationDbContext>().Database.ExecuteSqlCommand(query, Parametros)); }
public static int ExecuteCommand( this IDbContextScope ctx, string query, params object[] parameters ) { return(ctx.DbContexts.Get <NkapDbContext>().Database.ExecuteSqlCommand(query, parameters)); }
public static IQueryable <T> SqlQuery <T>( this IDbContextScope ctx, string query, params object[] parameters ) { return(ctx.DbContexts.Get <NkapDbContext>().Database.SqlQuery <T>(query, parameters).AsQueryable()); }
public static IQueryable <T> SqlQuery <T>( this IDbContextScope ctx, string query, params object[] Parametros ) { return(ctx.DbContexts.Get <ApplicationDbContext>().Database.SqlQuery <T>(query, Parametros).AsQueryable()); }
protected T RunInNewContextScope <T>(Func <T> function) { using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create(DbContextScopeOption.ForceCreateNew)) { T result = function(); dbContextScope.SaveChanges(); return(result); } }
public NewClientViewModel(IDbContextScope dbContext) { _dbContext = dbContext; AddClientCommand = new DelegateCommand(AddClient, PropertiesNotNull) .ObservesProperty(() => Name) .ObservesProperty(() => LastName) .ObservesProperty(() => Age); }
public HomeViewModel(IDbContextScope dbContext) { _dbContext = dbContext; OrderByAgeCommand = new DelegateCommand(OrderByAge); OrderByIdCommand = new DelegateCommand(OrderById); DeleteClientCommand = new DelegateCommand <Client>(DeleteClient); Clients = _dbContext.GetClients(); }
public DetectModifiedEntitiesAndUpdateParentScope(DbContext dbContext, IDbContextScope dbContextScope) { _dbContextScope = dbContextScope; var changeTracker = dbContext.ChangeTracker; changeTracker.DetectChanges(); if (changeTracker.HasChanges()) { _modifiedEntries = changeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted).ToArray(); } }
/// <summary> /// Deletes the specified storage. /// </summary> /// <param name="storage">The instance of <see cref="Storage" /> type to delete.</param> /// <returns> /// The deleted instance of <see cref="Storage"/> type. /// </returns> public async Task <Storage> DeleteStorage(Storage storage) { using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { IStorageRepository storageRepository = scope.GetRepository <IStorageRepository>(); await storageRepository.DeleteAsync(storage.ID); scope.Commit(); } return(storage); }
/// <summary> /// Deletes the specified catalog. /// </summary> /// <param name="catalog">The instance of <see cref="Catalog" /> type to delete.</param> /// <returns> /// The deleted instance of <see cref="Catalog"/> type. /// </returns> public async Task <Catalog> DeleteCatalog(Catalog catalog) { using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); await catalogRepository.DeleteAsync(catalog.ID); scope.Commit(); } return(catalog); }
/// <summary> /// Deletes the specified catalog entry. /// </summary> /// <param name="entry">The instance of <see cref="CatalogEntry" /> type to delete.</param> /// <returns> /// The deleted instance of <see cref="CatalogEntry"/> type. /// </returns> public async Task <CatalogEntry> DeleteCatalogEntry(CatalogEntry entry) { using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, true)) { IFileRepository fileRepository = scope.GetRepository <IFileRepository>(); await fileRepository.DeleteAsync(entry.ID); scope.Commit(); } return(entry); }
public TDbContext CreateDbContext <TDbContext>(IDbContextScope dbContextScope, bool readOnly) where TDbContext : DbContext { var interceptor = readOnly ? _dbContextReadOnlyInterceptor : _dbContextInterceptor; var proxyGenerationOptions = new ProxyGenerationOptions(interceptor); var constructorArgs = _ambientDbContextArgumentFactory.CreateDbContextArguments <TDbContext>(); var additionalInterfacesToProxy = new[] { typeof(IDbContextProxyBypass) }; var proxy = (TDbContext)proxyGenerator.CreateClassProxy(typeof(TDbContext), additionalInterfacesToProxy, proxyGenerationOptions, constructorArgs, interceptor); return(proxy); }
protected T RunInContextScope <T>(Func <T> function, bool isReadOnly = false) { if (isReadOnly) { using (IDbContextReadOnlyScope dbContextScope = _dbContextScopeFactory.CreateReadOnly()) { return(function()); } } else { using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create()) { T result = function(); dbContextScope.SaveChanges(); return(result); } } }
/// <summary> /// Gets storage by initial instance set. /// </summary> /// <param name="storage">The initial storage set.</param> /// <returns>The instance of <see cref="Storage"/> type.</returns> public async Task <Storage> GetStorage(Storage storage) { StorageContract storageContract = null; CatalogContract catalogContract = null; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, false)) { IStorageRepository storageRepository = scope.GetRepository <IStorageRepository>(); storageContract = await storageRepository.GetAsync(storage.ID); ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); catalogContract = await catalogRepository.GetAsync(storage.ID); } storage = await this.mapper.MapNewAsync <StorageContract, Storage>(storageContract); storage = await this.mapper.MapAsync(catalogContract, storage); return(storage); }
/// <summary> /// Gets the catalog entry by the initial instance set. /// </summary> /// <param name="entry">The initial catalog entry set.</param> /// <returns>The instance of <see cref="CatalogEntry"/> type.</returns> public async Task <CatalogEntry> GetCatalogEntry(CatalogEntry entry) { FileContract fileContract = null; CatalogContract catalogContract = null; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, false)) { IFileRepository fileRepository = scope.GetRepository <IFileRepository>(); fileContract = await fileRepository.GetAsync(entry.ID); ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); catalogContract = await catalogRepository.GetAsync(fileContract.DirectoryID); } entry = await this.mapper.MapAsync(fileContract, entry); entry.Catalog = await this.mapper.MapAsync(catalogContract, entry.Catalog); return(entry); }
/// <summary> /// Gets the list of catalogs located in specified parent catalog. /// </summary> /// <param name="parent">The parent catalog of <see cref="CatalogRoot"/> type.</param> /// <param name="offset">The offset index.</param> /// <param name="limit">The number of records to return.</param> /// <returns> /// The list of instances of <see cref="Catalog" /> type. /// </returns> public async Task <IPaginable <Catalog> > GetCatalogs(CatalogRoot parent, int offset = 0, int limit = 20) { if (limit == 0) { return(await Task.FromResult(new PagedList <Catalog>() { Offset = offset, Limit = limit })); } IEnumerable <CatalogContract> data = null; int count = 0; CatalogContract contract = new CatalogContract() { ParentID = parent?.ID }; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, false)) { ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); await Task.WhenAll( Task.Run(async() => data = await catalogRepository.FindAsync(contract, offset, limit)), Task.Run(async() => count = await catalogRepository.GetCountAsync(contract))); } IPaginable <Catalog> result = (await this.mapper.MapNewAsync <CatalogContract, Catalog>(data)).Select(catalog => { catalog.Parent = (Catalog)parent; return(catalog); }).AsPaginable(); result.Offset = offset; result.Limit = limit; result.TotalCount = count; return(result); }
/// <summary> /// Gets the list of storages. /// </summary> /// <param name="offset">The offset index.</param> /// <param name="limit">The number of records to return.</param> /// <returns>The list of instances of <see cref="Storage"/> type.</returns> public async Task <IPaginable <Storage> > GetStorages(int offset = 0, int limit = 20) { if (limit == 0) { return(await Task.FromResult(new PagedList <Storage>() { Offset = offset, Limit = limit })); } IEnumerable <Storage> storages = null; int count = 0; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, false)) { IStorageRepository storageRepository = scope.GetRepository <IStorageRepository>(); ICatalogRepository catalogRepository = scope.GetRepository <ICatalogRepository>(); count = await storageRepository.GetCountAsync(); IEnumerable <StorageContract> data = await storageRepository.FindAsync(offset, limit); storages = await this.mapper.MapNewAsync <StorageContract, Storage>(data); storages = await Task.WhenAll(storages.Select(async storage => { CatalogContract catalogContract = await catalogRepository.GetAsync(storage.ID); return(await this.mapper.MapAsync(catalogContract, storage)); })); } IPaginable <Storage> result = storages.AsPaginable(); result.Offset = offset; result.Limit = limit; result.TotalCount = count; return(result); }
/// <summary> /// Gets the list of catalog entries located in specified catalog. /// </summary> /// <param name="catalog">The catalog of <see cref="CatalogRoot"/> type.</param> /// <param name="offset">The offset index.</param> /// <param name="limit">The number of records to return.</param> /// <returns> /// The list of instances of <see cref="CatalogEntry" /> type. /// </returns> public async Task <IPaginable <CatalogEntry> > GetCatalogEntries(CatalogRoot catalog, int offset = 0, int limit = 20) { if (limit == 0) { return(await Task.FromResult(new PagedList <CatalogEntry>() { Offset = offset, Limit = limit })); } IEnumerable <FileContract> data = null; int count = 0; FileContract contract = new FileContract() { DirectoryID = catalog.ID }; using (IDbContextScope scope = this.dataContextScopeFactory.CreateDbContextScope(this.connectionStrings.DataStorageDB, false)) { IFileRepository fileRepository = scope.GetRepository <IFileRepository>(); await Task.WhenAll( Task.Run(async() => data = await fileRepository.FindAsync(contract, offset, limit)), Task.Run(async() => count = await fileRepository.GetCountAsync(contract))); } IPaginable <CatalogEntry> result = (await this.mapper.MapNewAsync <FileContract, CatalogEntry>(data)).Select(entry => { entry.Catalog = (Catalog)catalog; return(entry); }).AsPaginable(); result.Offset = offset; result.Limit = limit; result.TotalCount = count; return(result); }
public void Begin() { _scope = _uow.CreateWithTransaction(IsolationLevel.Serializable); }
public void Setup() { _dbContextScopeFactory = Substitute.For<IDbContextScopeFactory>(); _ambientDbContextLocator = Substitute.For<IAmbientDbContextLocator>(); _photographRepository = Substitute.For<IPhotographRepository>(); _dbContext = Substitute.For<IDbContextScope>(); _dbContextScopeFactory.Create().Returns(_dbContext); _photographService = new PhotographServices(_dbContextScopeFactory, _photographRepository); }
public TodoItemsService2(IDbContextScope dbContextScope, IAmbientDbContextLocator ambientDbContextLocator, IUserAlertService userAlertService) { _dbContextScope = dbContextScope; _ambientDbContextLocator = ambientDbContextLocator; _userAlertService = userAlertService; }
public TodoItemsService3(IData<IAmbientDbContextLocator> data, IDbContextScope dbContextScope) { _data = data; _dbContextScope = dbContextScope; }