public static void Main(string[] args) { var host = BuildWebHost(args); // Нужно для получения DbContext using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { WebStoreContext context = services.GetRequiredService <WebStoreContext>(); // Инициализация первичных данных DbInitializer.Initialize(context); // Создаем роли и администратора DbInitializer.InitializeUsers(services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while seeding the database."); } } host.Run(); }
public RolesController(WebStoreContext contex) { _roleStore = new RoleStore <IdentityRole>(contex) { AutoSaveChanges = true }; }
public static void Main(string[] args) { #region Инициализация БД var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { WebStoreContext context = services.GetRequiredService <WebStoreContext>(); DbInitializer.Initialize(context); DbInitializer.InitializeUsers(services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "Oops. Something went wrong at DB initializing..."); } } host.Run(); #endregion #region По умолчанию //CreateHostBuilder(args).Build().Run(); #endregion }
public IActionResult Checkout([FromServices] WebStoreContext _db) { string _CartName = $"{User.Identity.Name}_cart"; var cookie = HttpContext.Request.Cookies[_CartName]; Cart cart = JsonConvert.DeserializeObject <Cart>(cookie); var order = new Order { UserName = User.Identity.Name, Contact = "1 5 Net Core st.", TotalPrice = cart.Items.Sum(pc => pc.Count * pc.Product.Price) }; _db.Orders.Add(order); foreach (var item in cart.Items) { var order_item = new OrderItem { Order = order, Product = _db.Products.FirstOrDefault(p => p.Id == item.Product.Id), //Product = item.Product, Quantity = item.Count }; _db.OrderItems.Add(order_item); } _db.SaveChanges(); HttpContext.Response.Cookies.Delete(_CartName); return(RedirectToAction("Catalog", "Home")); }
protected BaseUserApiController(WebStoreContext context) { _userStore = new UserStore <User>(context) { AutoSaveChanges = true }; }
public UsersController(WebStoreContext db) { _UserStore = new UserStore <User>(db) { AutoSaveChanges = true }; }
public static void Main(string[] args) { //CreateHostBuilder(args).Build().Run(); var host = BuildWebHost(args); // нужно для получения DbContext using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { WebStoreContext context = services.GetRequiredService <WebStoreContext>(); DbInitializer.Initialize(context); DbInitializer.InitializeUsers(services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "Oops. Something went wrong at DB initializing..."); } } host.Run(); }
public UsersController(WebStoreContext context) { _userStore = new UserStore <User>(context) { AutoSaveChanges = true }; }
public static void Main(string[] args) { //CreateHostBuilder(args).Build().Run(); //изначальная строка //разибваем начальную строку для вставки команды наполнения таблицы БД начальными данными IWebHost webHost = BuildWebHost(args); //конструкция с сайта майкрософт using (IServiceScope serviceScope = webHost.Services.CreateScope()) // нужно для получения DbContext { IServiceProvider serviceProvider = serviceScope.ServiceProvider; try { WebStoreContext webStoreContext = serviceProvider.GetRequiredService <WebStoreContext>(); //вся конструкция нужна ради команд из DbInitializer: DbInitializer.Initialize(webStoreContext); DbInitializer.InitializeUsers(serviceProvider); } catch (Exception ex) { ILogger logger = serviceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "Oops. Something went wrong at DB initializing..."); } } webHost.Run(); }
public WebStoreContextInitializer(WebStoreContext db, UserManager <User> userManager, RoleManager <Role> roleManager, ILogger <WebStoreContextInitializer> logger) { _logger = logger; _db = db; _userManager = userManager; _roleManager = roleManager; }
public UsersController(WebStoreContext DB, ILogger <UsersController> Logger) { _Logger = Logger; _UserStore = new UserStore <User>(DB) { AutoSaveChanges = true }; }
public UserController(WebStoreContext db, ILogger <UserController> logger) { _UserStore = new UserStore <User>(db) { AutoSaveChanges = true }; this._Logger = logger; }
public UsersController(WebStoreContext dbContext, ILogger <UsersController> logger) { _logger = logger; _userStore = new UserStore <User>(dbContext) { AutoSaveChanges = true }; }
public static void MyClassInitialize(TestContext testContext) { DatabaseInitializer.InitializeDatabase(); // warm up connection object id = new WebStoreContext() .Db.ExecuteScalar("select id from customer where id=@0", 1); }
public static void InitializeDatabase() { // create database if it doesn't exist Database.SetInitializer<WebStoreContext>(new WebStoreContextInitializer()); // force connection to be fired once var customer = new WebStoreContext().Customers.FirstOrDefault(); }
public static void InitializeDatabase() { // create database if it doesn't exist Database.SetInitializer <WebStoreContext>(new WebStoreContextInitializer()); // force connection to be fired once var customer = new WebStoreContext().Customers.FirstOrDefault(); }
public ServerClientFixture() { // Arrange Server = new TestServer(new WebHostBuilder() .UseStartup <TestStartup>()); Context = Server.Host.Services.GetRequiredService <WebStoreContext>(); Client = Server.CreateClient(); }
public UnitOfWork() { _context = new WebStoreContext(); ProductRepository = new ProductPepository(_context); CategoryRepository = new CategoryRepository(_context); AuthenticationRepository = new AuthenticationRepository(_context); UserRepository = new UserRepository(_context); GroupRepository = new GroupRepository(_context); }
public void Find() { using (var context = new WebStoreContext()) { var cust = context.Db.Find <Customer>(1, "Customers", "Id"); Assert.IsNotNull(cust, context.Db.ErrorMessage); Assert.AreEqual(cust.LastName, "Strahl"); } }
public void Find() { using (var context = new WebStoreContext()) { var cust = context.Db.Find<Customer>(1, "Customers", "Id"); Assert.IsNotNull(cust,context.Db.ErrorMessage); Assert.AreEqual(cust.LastName, "Strahl"); } }
/// <summary> /// Vezérlő példányosítása. /// </summary> /// <param name="context">Entitásmodell.</param> public ProductController(WebStoreContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } _context = context; }
public UserOrdersService(WebStoreContext context, IMapper mapper, UserManager <User> userManager, SignInManager <User> signInManager) : base(context, mapper) { this.userManager = userManager; this.signInManager = signInManager; }
/// <summary> /// Vezérlő példányosítása. /// </summary> /// <param name="context">Entitásmodell.</param> public RentController(WebStoreContext context, SignInManager <Customer> signInManager) { if (context == null) { throw new ArgumentNullException(nameof(context)); } _context = context; _signInManager = signInManager; }
public WebStoreContextInitializer( WebStoreContext db, UserManager <User> UserManager, RoleManager <IdentityRole> RoleManager) { _db = db; _UserManager = UserManager; _RoleManager = RoleManager; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, WebStoreContext context) { app.UseAuthentication(); app.UseMiddleware <AuthenticatedTestRequestMiddleware>(); // automatikus "bejelentkezés" app.UseMvc(); TestDbInitializer.Initialize(context); }
public WebStoreContextInitializer( WebStoreContext db, UserManager <User> UserManager, RoleManager <Role> RoleManager, ILogger <WebStoreContextInitializer> Logger) { _db = db; _UserManager = UserManager; _RoleManager = RoleManager; _Logger = Logger; }
public void SqlStoredProcedureToEntityList() { using (var context = new WebStoreContext()) { IEnumerable <Customer> customers = context.Db.ExecuteStoredProcedureReader <Customer>("GetCustomers", // named parameter requires CreateParameter context.Db.CreateParameter("@cCompany", "W%")); Assert.IsNotNull(customers, "Customers should not be null: " + context.Db.ErrorMessage); Assert.IsTrue(customers.Count() > 0, "Customer count should be greater than 0"); } }
public string GetPickUpPoints() { List <PickUpPoint> pickUpPointsJson = new List <PickUpPoint>(); using (WebStoreContext db = new WebStoreContext()) { db.PickUpPoints.ToList().ForEach(point => pickUpPointsJson. Add(point)); } return(JsonConvert.SerializeObject(pickUpPointsJson)); }
public List <Product> SelectOneById(int id) { var product = new List <Product>(); using (var db = new WebStoreContext()) { // Read product = db.Products .OrderBy(p => p.Id) .ToList(); } return(product); }
public static void Initialize(WebStoreContext context) { context.Database.EnsureCreated(); if (context.Products.Any()) { return; } using (var transaction = context.Database.BeginTransaction()) { foreach (var section in TestData.Sections) { context.Sections.Add(section); } context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Sections] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Sections] OFF"); transaction.Commit(); } using (var transaction = context.Database.BeginTransaction()) { foreach (var brand in TestData.Brands) { context.Brands.Add(brand); } context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Brands] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Brands] OFF"); transaction.Commit(); } using (var transaction = context.Database.BeginTransaction()) { foreach (var product in TestData.Products) { context.Products.Add(product); } context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Products] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Products] OFF"); transaction.Commit(); } }
public void ExecuteStoreQuery() { using (var context = new WebStoreContext()) { var t = context.Database.SqlQuery <Customer>("select * from Customers where id = {0}", 1).FirstOrDefault(); var watch = Stopwatch.StartNew(); var custs = context.Database.SqlQuery <Customer>("select * from Customers where entered > {0}", new DateTime(2000, 1, 1)); var custList = custs.ToList(); watch.Stop(); Assert.IsNotNull(custList); Console.WriteLine(custList.Count); Console.WriteLine(watch.ElapsedMilliseconds); } }
public void FindTest() { using (var context = new WebStoreContext()) { var t = context.Db.Find <Customer>("select id,firstname,lastname from Customers where id = @0", 1); Console.WriteLine(t.Company); var watch = Stopwatch.StartNew(); var custs = context.Db.Query <Customer>("select * from Customers where entered > @0", new DateTime(2000, 1, 1)).ToList(); watch.Stop(); Assert.IsNotNull(custs); Console.WriteLine(custs.Count); Console.WriteLine(watch.ElapsedMilliseconds); } }
public void FindTest() { using (var context = new WebStoreContext()) { var t = context.Db.Find<Customer>("select id,firstname,lastname from Customers where id = @0", 1); Console.WriteLine(t.Company); var watch = Stopwatch.StartNew(); var custs = context.Db.Query<Customer>("select * from Customers where entered > @0", new DateTime(2000, 1, 1)).ToList(); watch.Stop(); Assert.IsNotNull(custs); Console.WriteLine(custs.Count); Console.WriteLine(watch.ElapsedMilliseconds); } }
public void EntityLinqQuery() { var context = new WebStoreContext(); DateTime newDateTime = new DateTime(1900, 1, 1); var t = context.Customers.Where(cust=> cust.Id == 1).FirstOrDefault(); context.Dispose(); context = new WebStoreContext(); var watch = Stopwatch.StartNew(); newDateTime = new DateTime(2000, 1, 1); var custList = context.Customers.Where(cust => cust.Entered > newDateTime).ToList(); watch.Stop(); Assert.IsNotNull(custList); Console.WriteLine(custList.Count); Console.WriteLine(watch.ElapsedMilliseconds); }
public void SqlStoredProcedureToEntityList() { using (var context = new WebStoreContext()) { IEnumerable<Customer> customers = context.Db.ExecuteStoredProcedureReader<Customer>("GetCustomers", // named parameter requires CreateParameter context.Db.CreateParameter("@cCompany","W%")); Assert.IsNotNull(customers, "Customers should not be null: " + context.Db.ErrorMessage); Assert.IsTrue(customers.Count() > 0, "Customer count should be greater than 0"); } }
public void SqlStoredProcedureReader() { using (var context = new WebStoreContext()) { DbDataReader reader = context.Db.ExecuteStoredProcedureReader("GetCustomers", // named parameter requires CreateParameter context.Db.CreateParameter("@cCompany", "W%")); Assert.IsNotNull(reader, "Reader should not be null: " + context.Db.ErrorMessage); Assert.IsTrue(reader.HasRows, "Reader should have rows"); while (reader.Read()) { var company = reader["Company"] as string; var entered = (DateTime) reader["Entered"]; Console.WriteLine(company + " " + entered.ToString("d")); } } }
public void ExecuteStoreQuery() { using (var context = new WebStoreContext()) { var t = context.Database.SqlQuery<Customer>("select * from Customers where id = {0}", 1).FirstOrDefault(); var watch = Stopwatch.StartNew(); var custs = context.Database.SqlQuery<Customer>("select * from Customers where entered > {0}", new DateTime(2000, 1, 1)); var custList = custs.ToList(); watch.Stop(); Assert.IsNotNull(custList); Console.WriteLine(custList.Count); Console.WriteLine(watch.ElapsedMilliseconds); } }
public void SqlStoredProcedureNonQueryReturnValues() { using (var context = new WebStoreContext()) { var countParm = context.Db.CreateParameter("@nCount", 0, parameterDirection: System.Data.ParameterDirection.Output); var returnValueParm = context.Db.CreateParameter("@returnValue", 0, parameterDirection: System.Data.ParameterDirection.ReturnValue); int result = context.Db.ExecuteStoredProcedureNonQuery("GetCustomerCount", // named parameter requires CreateParameter context.Db.CreateParameter("@cCompany", "W%"), countParm, returnValueParm); Assert.IsFalse(result == -1, "result shouldn't be -1. " + context.Db.ErrorMessage); Console.WriteLine("Count value: " + countParm.Value); Console.WriteLine("Return Value: " + returnValueParm.Value); } }