public async Task <IEnumerable <Bet> > GetBetsWithActualResult() { DbContext dbContext = _dbContextFactory.Create(); FilterDefinition <Collections.Bet> filter = new ExpressionFilterDefinition <Collections.Bet>(b => b.ActualResult != null); return(await dbContext.GetCollection <Collections.Bet>().Find(filter).ToListAsync()); }
public async Task SeedGamesAsync() { await using var mnpContext = _contextFactory.Create(); var httpClient = new HttpClient(); for (var i = 0; i <= 300; i += 100) { var teseraGames = await httpClient.GetFromJsonAsync <GameTeseraResource[]>( $"https://api.tesera.ru/games?offset={i}&limit=100"); teseraGames = teseraGames.Where(g => g.TeseraId.ToString() != g.Title).ToArray(); foreach (var teseraGame in teseraGames) { if (await mnpContext.Games.AnyAsync(g => g.Name == teseraGame.Title)) { continue; } var game = teseraGame.ToGame(); await mnpContext.Games.AddAsync(game); //TODO: Implement file upload; } } await mnpContext.SaveChangesAsync(); }
public async Task <IEnumerable <User> > AllAsync() { DbContext dbContext = _dbContextFactory.Create(); IEnumerable <Collections.User> users = await dbContext.GetCollection <Collections.User>().Find(FilterDefinition <Collections.User> .Empty).ToListAsync(); return(users); }
public async Task <User> GetAsync(Guid id) { DbContext dbContext = _dbContextFactory.Create(); FilterDefinition <Collections.User> filter = new ExpressionFilterDefinition <Collections.User>(u => u.Id == id); Collections.User user = await dbContext.GetCollection <Collections.User>().Find(filter).SingleOrDefaultAsync(); return(user); }
public void ChangeProfile_ExistingIDSameEMail_UpdatedProfileHasValidData(int userID, string eMail) { var testDatabaseContext = DbContextFactory.Create(); var timeProviderMock = new Mock <ITimeProvider>(); timeProviderMock.Setup(p => p.Now()).Returns(new DateTime(2016, 1, 1)); var changeProfileDTO = new ChangeProfileDTO { EMail = eMail, City = "Test city", About = "Something about me", Footer = "Ultra-rare funny footer" }; var profileService = new ProfileService(testDatabaseContext, timeProviderMock.Object); profileService.ChangeProfile(userID, changeProfileDTO); var updatedProfile = profileService.GetProfileByUserID(userID); Assert.Equal(changeProfileDTO.EMail, updatedProfile.EMail); Assert.Equal(changeProfileDTO.City, updatedProfile.City); Assert.Equal(changeProfileDTO.About, updatedProfile.About); Assert.Equal(changeProfileDTO.Footer, updatedProfile.Footer); }
public async Task <TeamMetadata> UpsertAsync(Guid id, Action <TeamMetadata> setValues) { DbContext dbContext = DbContextFactory.Create(); FilterDefinition <Collections.TeamMetadata> filter = new ExpressionFilterDefinition <Collections.TeamMetadata>(collection => collection.Id == id); Collections.TeamMetadata documentToUpdate = await dbContext.GetCollection <Collections.TeamMetadata>().Find(filter).SingleOrDefaultAsync(); if (documentToUpdate != null) { setValues(documentToUpdate); await BeforeUpdate(documentToUpdate, dbContext); await dbContext.GetCollection <Collections.TeamMetadata>().ReplaceOneAsync(filter, documentToUpdate); } if (documentToUpdate == null) { documentToUpdate = new Collections.TeamMetadata(); setValues(documentToUpdate); await BeforeInsert(documentToUpdate, dbContext); await dbContext.GetCollection <Collections.TeamMetadata>().InsertOneAsync(documentToUpdate); } return(documentToUpdate); }
public List <Barcode> Search(int lotId) { using (PCBVIEntities context = DbContextFactory.Create()) { var query = from x in context.LotBarCodes select new { Lot = x.Lot, Barcode = x.Barcode, LotName = x.Lot.LotCode, ItemName = x.Barcode.Item.Name, ErrorType = x.Barcode.ErrorCode.ErrorType.Name }; if (lotId != 0) { query = query.Where(x => x.Lot.LotId == lotId); } foreach (var x in query) { x.Barcode.LotName = x.LotName; x.Barcode.ItemName = x.ItemName; x.Barcode.ErrorTypeName = x.ErrorType; } var list = query.ToList(); return(list.ConvertAll(x => x.Barcode)); } }
//RETRIEVE public List <Address> GetAddress(int custnum) //by CUSTOMER ID# { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { List <Address> addressDetails = new List <Address>(); //RETRIEVE BY CUSTOMER NUMBER var query = from Address a in context.Address where a.CustomerDetailsId == custnum select a; Console.WriteLine(query.Count()); foreach (Address addr in query) { Console.WriteLine($"Customer ID: {addr.CustomerDetailsId}"); //Console.WriteLine($"Customer ID: {addr.CustomerDetails.Id}"); Console.WriteLine($"Address ID #: {addr.Id}"); Console.WriteLine($"Address Type: {addr.Addresstype}"); Console.WriteLine($"Street #: {addr.Street}"); addressDetails.Add(addr); } return(addressDetails); } catch (Exception) { Console.WriteLine("Unable to retrieve addresses."); return(null); } } }
public string DeleteResource(string resourceId) { try { DbContext dc = DbContextFactory.Create(); var resource = dc.Set <T_Resource>().Where(a => a.ID == resourceId).FirstOrDefault(); if (resource == null) { return(JsonConvert.SerializeObject(Result.Fail(msg: "数据库无此数据,删除失败!"))); } var price = dc.Set <T_ResourcePrice>().Where(a => a.ResourceID == resourceId).FirstOrDefault(); if (price != null) { dc.Set <T_ResourcePrice>().Remove(price); } dc.Set <T_Resource>().Remove(resource); dc.SaveChanges(); return(JsonConvert.SerializeObject(Result.Success(msg: "删除成功"))); //if (dc.SaveChanges() > 0) //{ // return JsonConvert.SerializeObject(Result.Success(msg: "删除成功")); //} //else //{ // return JsonConvert.SerializeObject(Result.Fail(msg: "删除失败,有坑!")); //} } catch (Exception ex) { return(JsonConvert.SerializeObject(Result.Exception(msg: "删除异常,没啥好说的,比如说有图片信息这些!", exmsg: ex.StackTrace))); } }
public int GetCount() { using (DbContext entities = DbContextFactory.Create(NameOrConnectionString, Model)) { return(entities.Set <T>().Count()); } }
//RETRIEVE public void GetLineItem(int id) //by line id { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { //RETRIEVE BY id var query = from LineItem l in context.LineItem where l.Id == id //remove this line to retireve all select l; try { foreach (LineItem line in query) { Console.WriteLine($"\tLine ID: {line.Id}"); Console.WriteLine($"\tProduct: {line.ProductDetails}"); //Console.WriteLine($"\tOrder ID: {line.OrderDetailsId}"); Console.WriteLine($"\tQty: {line.Quantity}"); Console.WriteLine($"\tDiscount: {line.Discount}"); } } catch (Exception) { Console.WriteLine("No line item found."); } } }
//REMOVE public void RemoveLineItem(int id) { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { //Locate line id with line id = id passed var linequery = context.LineItem.FirstOrDefault(x => x.Id == id); try { //Chec if the queried ID = passed id if (linequery == null) { Console.WriteLine("Line does not exist"); } else if (linequery.Id == id) { context.LineItem.Remove(linequery); context.SaveChanges(); Console.WriteLine($"Line ID {id} removed successfully"); } } catch (Exception) { Console.WriteLine("Unable to delete line."); } } }
//UPDATE public void UpdateLineItem(LineItem updatedLine) { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { //Locate customer var query = context.LineItem.FirstOrDefault(a => a.Id == updatedLine.Id); //Console.WriteLine($"Passed Line ID {updatedLine.Id}"); //Console.WriteLine($"Queried Line ID {query.Id}"); //Update: query.ProductDetails = updatedLine.ProductDetails; query.Quantity = updatedLine.Quantity; //query.OrderDetailsId = updatedLine.OrderDetailsId; query.Discount = updatedLine.Discount; //If Id matches... if (query.Id == updatedLine.Id) { context.Entry(query).State = EntityState.Modified; context.SaveChanges(); Console.WriteLine($"Line ID# {updatedLine.Id} updated successfully."); } } catch (Exception) { Console.WriteLine("\t** Unable to update Line."); } } }
public async Task <Core.Domain.RankingSnapshot> GetNewestAsync() { return(await DbContextFactory.Create().GetCollection <RankingSnapshot>() .AsQueryable() .OrderByDescending(r => r.Timestamp) .FirstOrDefaultAsync()); }
private async Task <List <VmCustomer> > getCustomersAsync(int?id, string name) { var custVms = new List <VmCustomer>(); try { var predicateRole = PredicateBuilder.New <Customer>(); if (id.HasValue) { predicateRole = predicateRole.And(x => x.Id == id.Value); } if (!string.IsNullOrEmpty(name)) { predicateRole = predicateRole.And(x => x.Name.IndexOf(name) >= 0); } using (var custService = new CustomerService(DbContextFactory.Create())) { var custs = custService.GetAll().AsExpandable().Where(predicateRole).ToList(); custs.ForEach(x => custVms.Add(ViewModelFactory.Create <Customer, VmCustomer>(x))); return(custVms); } } catch (Exception ex) { this._logger.Error(ex.Message); throw; } }
//UPDATE-------- public void UpdateProduct(Product prod) { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { var prquery = context.Product.FirstOrDefault(a => a.Id == prod.Id); Console.WriteLine($"Passed Address ID {prod.Id}"); Console.WriteLine($"Queried Address ID {prquery.Id}"); prquery.Name = prod.Name; prquery.Price = prod.Price; if (prquery.Id == prod.Id) { context.Entry(prquery).State = EntityState.Modified; context.SaveChanges(); Console.WriteLine($"Product ID# {prod.Id} updated successfully."); } } catch (Exception) { Console.WriteLine("Unable to update product."); } } }
public void LineItemUpdateTest() { //Arrange ... LineItem updateLine = new LineItem { Id = 5, Quantity = 100 }; LineItemManager mgr = new LineItemManager(); using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { //Arrange mgr.UpdateLineItem(updateLine); //Act ... locate the entry in dbcontext var query = from LineItem l in context.LineItem where l.Id == updateLine.Id select l; //Assert... compare - updated details to the original update request Assert.AreEqual(updateLine.Id, query.First().Id); Assert.AreEqual(updateLine.Quantity, query.First().Quantity); } }//end update test
//REMOVE ***********************CONSTRAINTS************************************ public void RemoveShipMethod(int id) { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { var methd = context.ShippingMethod.FirstOrDefault(m => m.Id == id); if (methd.Id == id) { //check for any orders that have method var ord = context.OrderDetails.Select(o => o.Shipmethod.Id == id); Console.WriteLine(ord.Count()); context.ShippingMethod.Remove(methd); context.SaveChanges(); Console.WriteLine($"ShippingMethod ID {id} removed successfully"); } } catch (Exception) { Console.WriteLine("Unable to delete shipping method."); } } }
public List <T> GetAll() { using (DbContext entities = DbContextFactory.Create(NameOrConnectionString, Model)) { return(entities.Set <T>().ToList()); } }
/// <summary> /// Gets the divisions. /// </summary> /// <returns></returns> public async Task <List <Division> > GetDivisions() { using (var context = DbContextFactory.Create()) { return(await context.Division.ToListAsync()); } }
public List <S> Select <S>(Expression <Func <T, S> > selector) { using (DbContext entities = DbContextFactory.Create(NameOrConnectionString, Model)) { return(entities.Set <T>().Select(selector).ToList()); } }
//REMOVE --> can we change this function to be handled in the UPDATE function? public void CancelOrder(int id) { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { //Locate order var query = context.OrderDetails.FirstOrDefault(x => x.Id == id); try { //Check if the queried ID = passed id if (query == null) { Console.WriteLine("Order does not exist"); } if (query.OrderStatus == OrderDetails.ShippingStatus.COMPLETED) { Console.WriteLine("Cannot cancel order -- already completed."); } else if (query.Id == id) { query.OrderStatus = OrderDetails.ShippingStatus.CANCELED; //Update the order to CANCELED UpdateOrder(query); context.SaveChanges(); Console.WriteLine($"Order ID {id} cancelled successfully"); } } catch (Exception) { Console.WriteLine("\t*** Unable to cancel order."); } } }
//RETRIEVE-------- public IEnumerable <Product> GetProducts(Instructions instructions) { //view amt //start val //category using (var context = DbContextFactory.Create()) { var query = context.Product.ToList(); Console.WriteLine(instructions.category); switch (instructions.category) { case "all": query = context.Product .OrderBy(n => n.Id).Skip(instructions.startVal).Take(instructions.viewAmt).ToList(); break; default: query = context.Product .OrderBy(n => n.Id).Where(c => c.Category == instructions.category) .Skip(instructions.startVal).Take(instructions.viewAmt).ToList(); break; } return(query); } }
//UPDATE public void UpdateOrder(OrderDetails ord) { LineItemManager linemgr = new LineItemManager(); using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { //Locate order var query = context.OrderDetails.FirstOrDefault(a => a.Id == ord.Id); Console.WriteLine(query.Id); //Update values //If Id matches... if (query.Id == ord.Id) { Console.WriteLine("Query id matches passed value..."); query.OrderStatus = ord.OrderStatus; query.Shipmethod.Id = ord.Shipmethod.Id; //Then Save changes to order context.Entry(query).State = EntityState.Modified; context.SaveChanges(); if (ord.Lineitems != null) { Console.WriteLine("UPDATED ORDER HAS LINES "); //Update each line item foreach (LineItem l in ord.Lineitems) { //if new line item, create it -- will contain order ID if (l.Id == 0) { linemgr.CreateLineItem(l); } else { //Update linemgr.UpdateLineItem(l); } }// end foreach ql @ line (in query) } Console.WriteLine($"Order ID# {ord.Id} updated successfully."); }//end id match } catch (Exception) { Console.WriteLine("\t** Unable to update Order."); } } }//end update
//UPDATE public void UpdateAddress(Address address) { using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { var addr = context.Address.FirstOrDefault(a => a.Id == address.Id); Console.WriteLine($"Passed Address ID {address.Id}"); Console.WriteLine($"Queried Address ID {addr.Id}"); addr.CustomerDetails.Id = address.CustomerDetails.Id; addr.Addresstype = address.Addresstype; addr.Street = address.Street; addr.City = address.City; addr.State = address.State; addr.Zip = address.Zip; if (addr.Id == address.Id) { context.Entry(addr).State = EntityState.Modified; context.SaveChanges(); Console.WriteLine($"Address ID# {address.Id} updated successfully."); } } catch (Exception) { Console.WriteLine("Unable to update."); } } }
//CREATE //This should take CUSTOMER ID, SHIPPING DETAILS, ARRAY OF LINE ITEMS & CREATE ORDER public void CreateOrder(OrderDetails newOrder) { //Console.WriteLine($"Order date: {newOrder.Date}"); LineItemManager linemgr = new LineItemManager(); using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { try { //Add order context.OrderDetails.Add(newOrder); context.SaveChanges(); //For each line in newOrder, update it with new ID foreach (LineItem l in newOrder.Lineitems) { //linemgr.UpdateLineItem(l); //Console.WriteLine(l.OrderDetailsId); } Console.WriteLine($"Order #{newOrder.Id} added."); } catch (Exception) { Console.WriteLine("Unable to add order...."); } } }
//불량인 애들만 public List <Barcode> SearchFail(int lotId, DateTime fromDate, DateTime toDate) { using (var context = DbContextFactory.Create()) { DateTime addToDate = toDate.AddDays(1); var query = from x in context.LotBarCodes where x.Barcode.State.Equals("Fail") && (x.Barcode.InspectionDate >= fromDate.Date && x.Barcode.InspectionDate < addToDate.Date) select new { Barcode = x.Barcode, LotBarCode = x }; if (lotId != 0) { query = query.Where(x => x.LotBarCode.LotId == lotId); } foreach (var x in query) { x.Barcode.LotId = x.LotBarCode.LotId; } var list = query.ToList(); return(list.ConvertAll(x => x.Barcode)); } }
public void GetCustomerOrdersTest() { int m = 1; OrderDetails.ShippingStatus orderstatus = OrderDetails.ShippingStatus.PROCESSING; using (var context = DbContextFactory.Create()) { //Act var ord = context.OrderDetails .Include(l => l.Lineitems).ThenInclude(p => p.ProductDetails) .Where(o => o.OrderStatus == orderstatus && o.CustomerDetails.Id == m) .Select(x => new { OrderId = x.Id, Date = x.OrderDate, CustomerId = x.CustomerDetails.Id, OrderStat = x.OrderStatus, Total = x.Lineitems.Sum(item => item.Quantity * item.ProductDetails.Price) }); //Act ... RETRIEVE Assert.AreEqual(orderstatus, ord.First().OrderStat); Assert.AreEqual(22.99, ord.First().Total); } }
public void ShipMethodUpdateTest() { int id = 3; //Arrange ... ShippingMethod newMethod = new ShippingMethod { Id = id, Method = "Ground" }; ShipMethodManager mgr = new ShipMethodManager(); using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { //Arrange //mgr.UpdateShipMethod(newMethod); //Act ... locate the entry in dbcontext var query = from ShippingMethod m in context.ShippingMethod where m.Id == id select m; //Assert... compare - updated details to the original update request Assert.AreEqual(newMethod.Id, query.First().Id); Assert.AreEqual(newMethod.Method, query.First().Method); } }//end update test
public void CustomerUpdateTest() { int id = 10; //Arrange ... Customer updatedCust = new Customer { Id = id, Name = "Welding Professionals, Inc." }; CustomerManager mgr = new CustomerManager(); using (var context = DbContextFactory.Create()) //no 'NEW' b/c of static class { //Arrange mgr.UpdateCustomer(updatedCust); //Act ... locate the entry in dbcontext var query = from Customer c in context.Customer where c.Id == id select c; //Assert... compare - updated details to the original update request Assert.AreEqual(updatedCust.Name, query.First().Name); } }//end update test
private void PopulateGenres(DbContextFactory dbContextFactory) { using (var dbContext = dbContextFactory.Create()) { dbContext.Genres.Add(new Genre() { Name = "Pop", Description = "Test 1" }); dbContext.Genres.Add(new Genre() { Name = "Rock", Description = "Test 2" }); dbContext.Genres.Add(new Genre() { Name = "Rap", Description = "Test 3" }); dbContext.SaveChanges(); } }
private void PopulateAlbums(DbContextFactory dbContextFactory) { this.PopulateGenres(dbContextFactory); using (var dbContext = dbContextFactory.Create()) { var pop = dbContext.Genres.FirstOrDefault(g => g.Name == "Pop"); var rock = dbContext.Genres.FirstOrDefault(g => g.Name == "Rock"); var rap = dbContext.Genres.FirstOrDefault(g => g.Name == "Rap"); dbContext.Albums.Add(this.CreateTestAlbum(pop)); dbContext.Albums.Add(this.CreateTestAlbum(pop)); dbContext.Albums.Add(this.CreateTestAlbum(rock)); dbContext.Albums.Add(this.CreateTestAlbum(rock)); dbContext.Albums.Add(this.CreateTestAlbum(rock)); dbContext.Albums.Add(this.CreateTestAlbum(rock)); dbContext.Albums.Add(this.CreateTestAlbum(rock)); dbContext.Albums.Add(this.CreateTestAlbum(rap)); dbContext.Albums.Add(this.CreateTestAlbum(rap)); dbContext.SaveChanges(); } }
private static BasicDbContext Create(DbContextFactory factory, InjectionSet injectionSet) { return factory.Create<BasicDbContext>(injectionSet, "EntityFrameworkInject"); }