public User GetUser(Guid userId) { /* * An example of using DbContextScope for read-only queries. * Here, we access the Entity Framework DbContext directly from * the business logic service class. * * Calling SaveChanges() is not necessary here (and in fact not * possible) since we created a read-only scope. */ using (IDbContextReadOnlyScope dbContextScope = _dbContextScopeFactory.CreateReadOnly()) { 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 value provided for userId: [{userId}]. Couldn't find a user with this ID."); } return(user); } }
public static void Seed(UserManagementDbContext context) { AddUser(context, ValidUser1Mail, ValidUser1Password, "Abigail", ValidUser1Role); AddUser(context, ValidUser2Mail, ValidUser2Password, "Bethany", ValidUser2Role); AddUser(context, "*****@*****.**", "1a5g9j2k", "Chloe", UserRole.Regular); AddUser(context, "*****@*****.**", "kd94j7djdc83j", "Daisy", UserRole.Regular); }
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 }); } }
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 IEnumerable <User> GetUsers(params Guid[] userIds) { using (IDbContextReadOnlyScope dbContextScope = _dbContextScopeFactory.CreateReadOnly()) { UserManagementDbContext dbContext = dbContextScope.DbContexts.Get <UserManagementDbContext>(); return(dbContext.Users.Where(u => userIds.Contains(u.Id)).ToList()); } }
public UsersController(IUserLogic _IUserLogic, IConfiguration configuration, ILoggerManager logger, UserManagementDbContext userManagementDbContext) { _configuration = configuration; _auth = new AuthService(_configuration); iUserLogic = _IUserLogic; _logger = logger; _userManagementDbContext = userManagementDbContext; }
private static void AddUser(UserManagementDbContext context, string email, string password, string name, UserRole role) { var user = new User(EmailAddress.Create(email), Password.Create(password)) { Name = name, Role = role }; context.Users.Add(user); context.SaveChanges(); }
public void TestInitialize() { userManagementDbContext = CreateUserManagementDbContext(); var correlationIdProviderMock = new Mock <ITraceIdProvider>(); correlationIdProviderMock.Setup(x => x.TraceId).Returns(() => "666"); serviceUnderTest = new UsersService(userManagementDbContext, correlationIdProviderMock.Object, CreateAutoMapper()); }
public void UserDbContextCreated_AccessDate_DataIsReceived() { // Arrange using (UserManagementDbContext userDbContext = new UserManagementDbContext()) { // Act var roles = userDbContext.Roles.Where(e => true); // Assert Assert.NotNull(roles); } }
public void UpdateCreditScore(Guid userId) { using (IDbContextScope dbContextScope = _dbContextScopeFactory.Create()) { 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."); } // Simulate the calculation of a credit score taking some time Random random = new Random(Thread.CurrentThread.ManagedThreadId); Thread.Sleep(random.Next(300, 1000)); user.CreditScore = random.Next(1, 100); dbContextScope.SaveChanges(); } }
public UsersService(UserManagementDbContext context, ITraceIdProvider correlationIdProvider, IConfigurationProvider mapperConfiguration) { this.context = context; this.correlationIdProvider = correlationIdProvider; this.mapperConfiguration = mapperConfiguration; }
static void Main(string[] args) { //-- Poor-man DI - build our dependencies by hand for this demo DbContextScopeFactory dbContextScopeFactory = new DbContextScopeFactory(); AmbientDbContextLocator ambientDbContextLocator = new AmbientDbContextLocator(); UserRepository userRepository = new UserRepository(ambientDbContextLocator); UserCreationService userCreationService = new UserCreationService(dbContextScopeFactory, userRepository); UserQueryService userQueryService = new UserQueryService(dbContextScopeFactory, userRepository); UserEmailService userEmailService = new UserEmailService(dbContextScopeFactory); UserCreditScoreService userCreditScoreService = new UserCreditScoreService(dbContextScopeFactory); try { Console.WriteLine("This demo application will create a database named DbContextScopeDemo in the default SQL Server instance on localhost. Edit the connection string in UserManagementDbContext if you'd like to create it somewhere else."); Console.WriteLine("Press enter to start..."); Console.ReadLine(); //-- Demo of typical usage for read and writes Console.WriteLine("Creating a user called Mary..."); UserCreationSpec marysSpec = new UserCreationSpec("Mary", "*****@*****.**"); userCreationService.CreateUser(marysSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created user from the data store..."); User mary = userQueryService.GetUser(marysSpec.Id); Console.WriteLine("OK. Persisted user: {0}", mary); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbContextScopes Console.WriteLine("Creating 2 new users called John and Jeanne in an atomic transaction..."); UserCreationSpec johnSpec = new UserCreationSpec("John", "*****@*****.**"); UserCreationSpec jeanneSpec = new UserCreationSpec("Jeanne", "*****@*****.**"); userCreationService.CreateListOfUsers(johnSpec, jeanneSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created users from the data store..."); IEnumerable <User> createdUsers = userQueryService.GetUsers(johnSpec.Id, jeanneSpec.Id); Console.WriteLine("OK. Found {0} persisted users.", createdUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbContextScopes in the face of an exception. // If any of the provided users failed to get persisted, none should get persisted. Console.WriteLine("Creating 2 new users called Julie and Marc in an atomic transaction. Will make the persistence of the second user fail intentionally in order to test the atomicity of the transaction..."); UserCreationSpec julieSpec = new UserCreationSpec("Julie", "*****@*****.**"); UserCreationSpec marcSpec = new UserCreationSpec("Marc", "*****@*****.**"); try { userCreationService.CreateListOfUsersWithIntentionalFailure(julieSpec, marcSpec); Console.WriteLine("Done.\n"); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); } Console.WriteLine("Trying to retrieve our newly created users from the data store..."); IEnumerable <User> maybeCreatedUsers = userQueryService.GetUsers(julieSpec.Id, marcSpec.Id); Console.WriteLine("Found {0} persisted users. If this number is 0, we're all good. If this number is not 0, we have a big problem.", maybeCreatedUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of DbContextScope within an async flow Console.WriteLine("Trying to retrieve two users John and Jeanne sequentially in an asynchronous manner..."); // We're going to block on the async task here as we don't have a choice. No risk of deadlocking in any case as console apps // don't have a synchronization context. IList <User> usersFoundAsync = userQueryService.GetTwoUsersAsync(johnSpec.Id, jeanneSpec.Id).Result; Console.WriteLine("OK. Found {0} persisted users.", usersFoundAsync.Count); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of explicit database transaction. Console.WriteLine("Trying to retrieve user John within a READ UNCOMMITTED database transaction..."); // You'll want to use SQL Profiler or Entity Framework Profiler to verify that the correct transaction isolation // level is being used. User userMaybeUncommitted = userQueryService.GetUserUncommitted(johnSpec.Id); Console.WriteLine("OK. User found: {0}", userMaybeUncommitted); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of disabling the DbContextScope nesting behaviour in order to force the persistence of changes made to entities // This is a pretty advanced feature that you can safely ignore until you actually need it. Console.WriteLine("Will simulate sending a Welcome email to John..."); using (IDbContextScope parentScope = dbContextScopeFactory.Create()) { UserManagementDbContext parentDbContext = parentScope.DbContexts.Get <UserManagementDbContext>(); // Load John in the parent DbContext #if EF6 User john = parentDbContext.Users.Find(johnSpec.Id); #elif EFCore var john = parentDbContext.Users.SingleOrDefault(x => x.Id == johnSpec.Id); #endif Console.WriteLine("Before calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Now call our SendWelcomeEmail() business logic service method, which will // update John in a non-nested child context userEmailService.SendWelcomeEmail(johnSpec.Id); // Verify that we can see the modifications made to John by the SendWelcomeEmail() method Console.WriteLine("After calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Note that even though we're not calling SaveChanges() in the parent scope here, the changes // made to John by SendWelcomeEmail() will remain persisted in the database as SendWelcomeEmail() // forced the creation of a new DbContextScope. } Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demonstration of DbContextScope and parallel programming Console.WriteLine("Calculating and storing the credit score of all users in the database in parallel..."); userCreditScoreService.UpdateCreditScoreForAllUsers(); Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine(); Console.WriteLine("The end."); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
public UserRepository(UserManagementDbContext dbContext) : base(dbContext) { addresses = dbContext.Set <Address>(); }
static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); var optionsBuilder = new DbContextOptionsBuilder <UserManagementDbContext>(); //optionsBuilder.UseNpgsql("Server=10.137.114.199;Database=UserManagement;uid=postgres;pwd=CompanyName@2018"); optionsBuilder.UseNpgsql("Server=127.0.0.1;Database=AdminSite;uid=sa;pwd=sa"); using (UserManagementDbContext context = new UserManagementDbContext(optionsBuilder.Options)) { City ci = new City() { Id = "1", CityName = "cn" }; Capital c = new Capital() { City = ci, other = "2" }; context.Add(c); //Realm r = new Realm(); //r.RlmId = 1; //r.RealmName = "Realm1"; //context.Add<Realm>(r); Realm realm1 = context.Realms.Where(i => EF.Functions.ILike(i.RealmName, "r%")).FirstOrDefault(); Realm realm2 = context.Realms.Where(i => i.RealmName.Contains("realm1")).FirstOrDefault(); //AdminUser user = new AdminUser(); //user.Id = 1; //user.Name = "user1"; //user.Realm = r; //context.Add<AdminUser>(user); //Solution s1 = new Solution(); //s1.SlnId = 1; //s1.SolutionName = "sln1"; //RealmSolution realmSolution = new RealmSolution(); //realmSolution.RlmId = 1; //s1.RealmSolutions.Add(realmSolution); //context.Add(s1); context.SaveChanges(true); //AdminUser us = context.AdminUsers.Include(u=>u.Realm).Where(u => u.Id == 1).FirstOrDefault(); //Realm rl = context.Realms.Where(rlm => rlm.RlmId == 1).FirstOrDefault(); //Realm r2 = new Realm(); //r2.RlmId = 2; //r2.RealmName = "r1"; //context.SaveChanges(true); //Realm realm = context.Realms.Where(r => r.RlmId == 2).FirstOrDefault(); //realm.RealmSolutions = new List<RealmSolution>(); //realm.RealmSolutions.Add(new RealmSolution() { SlnId = 2 }); //context.Update(realm); //context.SaveChanges(true); } }
public BaseRepository(UserManagementDbContext dbContext) { this.dbContext = dbContext; entities = dbContext.Set <TEntity>(); }
private static void SeedData(UserManagementDbContext context, RoleManager <IdentityRole> roleManager) { roleManager.CreateAsync(new IdentityRole("Admin")).GetAwaiter().GetResult(); roleManager.CreateAsync(new IdentityRole("User")).GetAwaiter().GetResult(); context.SaveChanges(); }
public UsersController(UserManagementDbContext context) { _context = context; }
public EventSender(UserManagementDbContext dbContext, IEventBus eventBus) { this.dbContext = dbContext; this.eventBus = eventBus; }
public UsersController(UserManagementDbContext dbContext) { _dbContext = dbContext; }
public UserRepository(UserManagementDbContext context) : base(context) { }