public async Task <Response> Create(int StudentId, int GroupId) { using (var context = _applicationDbContextFactory.Create()) { var StudentGroup = context.StudentGroups.Where(i => i.StudentId == StudentId && i.GroupId == GroupId).FirstOrDefault(); if (StudentGroup != null) { return new ResponseObject <StudentGroup> { Status = 500, Message = "Студент в этой группе уже есть!" } } ; if (!context.Check <Student>(StudentId)) { return new Response { Status = 500, Message = "Такого студента нет!" } } ; if (!context.Check <Group>(GroupId)) { return new Response { Status = 500, Message = "Такой группы нет!" } } ; context.StudentGroups.Add(new StudentGroup { StudentId = StudentId, GroupId = GroupId }); context.SaveChanges(); return(new Response { Status = 100, Message = "Запрос успешно прошел." }); } }
public async Task <Response> Create(PaymentCreateModel model, ClaimsPrincipal claimsPrincipal) { using (var context = _applicationDbContextFactory.Create()) { var Entity = Mapper.Map <Payment>(model); var Group = context.GetGroupStudentId(model.StudentId, model.GroupId); var User = await _userManager.FindByNameAsync(claimsPrincipal.Identity.Name); Entity.UserId = User.Id; if (Entity.Sum > Group.OneMounthSum) { return(new Response { Status = 500, Message = "Сумма взноса больше суммы контракта" }); } if (context.StudentGroups.Any(i => i.GroupId == model.GroupId && i.StudentId == model.GroupId)) { return new Response { Status = 500, Message = "Студент не зарегистрирован в данной группе" } } ; var result = context.Add(Entity); context.SaveChanges(); context.PaymentHistories.Add(new PaymentHistory { Action = "Создание", PaymentId = result.Entity.Id, DateTime = DateTime.Now, UserId = User.Id }); context.SaveChanges(); return(new Response { Status = 100, Message = "Запрос прошел успешно" }); } }
public RandomData(IRepository <Person> personRepository, IApplicationDbContextFactory contextFactory) { _random = new Random(); _personRepository = personRepository; using (var context = contextFactory.Create(QueryTrackingBehavior.NoTracking)) { _personCount = personRepository.Count(context); } _indexes = new[] { 0, 1 }; _timerIntervals = new[] { 3000, 5000 }; _randomDataItems = _indexes.Select(_ => (RandomDataItem)null).ToArray(); _timers = _indexes.Select(index => new Timer(state => { var randomPersonIndex = GetNewRandomIndex(); using (var context = contextFactory.Create(QueryTrackingBehavior.NoTracking)) { _randomDataItems[index] = _personRepository .SkipTake(randomPersonIndex, 1, context, person => person.Group) .ToList() .Select(person => new RandomDataItem { Index = index, Id = person.Id, Person = $"{person.Forenames} {person.Surname}", Group = person.Group.Name }) .First(); } Changed(nameof(Data)); PushUpdates(); }, null, 0, _timerIntervals[index])).ToArray(); }
public IReadOnlyCollection <Person> GetFilteredListOfPeople(string filterText) { using (var context = _contextFactory.Create(QueryTrackingBehavior.NoTracking)) { if (string.IsNullOrEmpty(filterText)) { return(_personRepo .FetchAll(context, person => person.Group) .ToArray()); } var lowerFilterText = filterText.ToLowerInvariant(); var filteredQuery = _personRepo .Fetch(p => EF.Functions.Like(p.Forenames, $"%{lowerFilterText}%") || EF.Functions.Like(p.Surname, $"%{lowerFilterText}%") || EF.Functions.Like(p.Group.Name, $"%{lowerFilterText}%"), context, person => person.Group); if (filteredQuery.Any()) { return(filteredQuery.ToArray()); } return(_personRepo .FetchAll(context, person => person.Group) .AsEnumerable() .Where(p => p.Name.ToLowerInvariant().Contains(lowerFilterText) || p.Group.Name.ToLowerInvariant().Contains(lowerFilterText)) .ToArray()); } }
public async Task <IEnumerable <Person> > GetAll(RequestContext requestContext) { using (var context = dbContextFactory.Create()) { return(await context.Persons.ToListAsync(requestContext.CancelationToken)); } }
public async Task <Response> Create(CourseCreateModel courseCreateModel, ClaimsPrincipal claimsPrincipal) { using (var context = _applicationDbContextFactory.Create()) { var User = await _userManager.FindByNameAsync(claimsPrincipal.Identity.Name); var Course = Mapper.Map <Course>(courseCreateModel); if (!context.Check <City>(courseCreateModel.CityId)) { return new Response { Status = 500, Message = "Такого города нет!" } } ; if (context.Courses.Any(i => i.Name == Course.Name && i.CityId == courseCreateModel.CityId)) { return new Response { Status = 500, Message = "Такой курс уже есть в этом городе!" } } ; var Result = context.Courses.Add(Course); context.SaveChanges(); context.courseHistories.Add(new CourseHistory { Action = "Создание", CourseId = Result.Entity.Id, DateTime = DateTime.Now, UserId = User.Id }); context.SaveChanges(); return(new Response { Status = 100, Message = "Запрос успешно прошел." }); } }
public async Task <Response <List <AnalystsModel> > > StatusesAnalysts(AnalystsFilterModel model) { using (var context = _applicationDbContextFactory.Create()) { var Result = context.StatusesAnalys(model.StartDate, model.EndDate, model.CityId); var Models = Mapper.Map <List <AnalystsModel> >(Result); return(new Response <List <AnalystsModel> >(Models)); } }
public async Task RegisterUserAsync(ApplicationUser user, string registrationToken, CancellationToken cancellationToken = default(CancellationToken)) { using (var context = factory.Create()) { await context.DbSet <UserRegistration>().AddAsync(new UserRegistration { User = user, RegistrationToken = registrationToken }, cancellationToken); } }
/// <summary> /// Loads the <typeparamref name="TEntity"/> with <paramref name="id"/> from the database. /// This method is thread safe. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="id"></param> public TEntity Load <TEntity>(object id) where TEntity : class { using (var dbContext = _contextFactory.Create()) { dbContext.Configuration.ProxyCreationEnabled = false; dbContext.Configuration.LazyLoadingEnabled = false; var entity = dbContext.Set <TEntity>().Find(id); dbContext.Entry(entity).State = EntityState.Detached; return(entity); } }
public async Task SubscribeAsync(ApplicationUser user, Topic topic, CancellationToken cancellationToken = default(CancellationToken)) { await transport.SubscribeAsync(user, topic, cancellationToken); using (var context = factory.Create()) { await context.DbSet <UserTopic>().AddAsync(new UserTopic() { User = user, Topic = topic, SubscriptionDate = DateTime.UtcNow }, cancellationToken); await context.SaveChangesAsync(cancellationToken); } }
public async Task <ResponseObject <List <LeadCommentIndexModel> > > GetAll() { using (var context = _applicationDbContextFactory.Create()) { var LeadComments = context.LeadCommentsInclude(); var Models = Mapper.Map <List <LeadCommentIndexModel> >(LeadComments); return(new ResponseObject <List <LeadCommentIndexModel> > { Status = 100, Message = "Запрос прошел успешно", ResponseObj = Models }); } }
public async Task <IList <CustomerRole> > GetAllCustomerRoles(bool showHidden = false) { using (var context = dbContextFactory.Create()) { var customer = await context.DbSet <CustomerRole>() .ToListAsync(); if (customer == null) { return(null); } return(customer); } }
public async Task <ResponseObject <List <CityIndexModel> > > GetAll() { using (var context = _applicationDbContextFactory.Create()) { var Cities = context.Cities.ToList(); var Models = Mapper.Map <List <CityIndexModel> >(Cities); return(new ResponseObject <List <CityIndexModel> > { Status = 100, Message = "Запрос прошел успешно", ResponseObj = Models }); } }
public async Task <CustomerPassword> GetCurrentPassword(int customerId) { using (var context = dbContextFactory.Create()) { var customer = await context.DbSet <CustomerPassword>() .FirstOrDefaultAsync(x => x.CustomerId == customerId); if (customer == null) { return(null); } return(customer); } }
public override async Task <CloneScoreFormulaCommand> HandleAsync( CloneScoreFormulaCommand command, CancellationToken cancellationToken = default) { await using (var dbContext = _dbContextFactory.Create(command.UserId)) { var scoreFormulas = await dbContext.ScoreFormulas .Include(s => s.FormulaType) .Include(s => s.Coefficients) .ThenInclude(c => c.ExamLessonSection) .ThenInclude(e => e.Lesson) .Where(s => EF.Property <int>(s, "CreatedBy") == default) .ToListAsync(cancellationToken); var list = new List <ScoreFormula>(); foreach (var formula in scoreFormulas) { list.Add(new ScoreFormula(formula)); } dbContext.ScoreFormulas.AddRange(list); await dbContext.SaveChangesAsync(cancellationToken); } return(await base.HandleAsync(command, cancellationToken)); }
public override async Task <BulkCreateStudentCommand> HandleAsync( BulkCreateStudentCommand command, CancellationToken cancellationToken = default) { var contactTypes = new List <ContactType>(); await using (var dbContext = _dbContextFactory.Create(command.UserId)) { foreach (var subCommand in command.Commands) { await RemoveStudentIfExistsAsync(dbContext, subCommand.StudentNumber, command.UserId, cancellationToken); var classroom = await GetClassroomAsync(dbContext, subCommand.ClassroomId, cancellationToken); var student = subCommand.ToDomainModel(classroom); dbContext.Students.Add(student); contactTypes.AddRange(student.Contacts.Select(c => c.ContactType)); } dbContext.AttachRange(contactTypes.Distinct()); await dbContext.SaveChangesAsync(cancellationToken); } return(await base.HandleAsync(command, cancellationToken)); }
public override async Task <EditStudentCommand> HandleAsync( EditStudentCommand command, CancellationToken cancellationToken = default) { await using (var dbContext = _dbContextFactory.Create(command.UserId)) { await EnsureNotExistsAsync(command, cancellationToken); var student = await GetStudentAsync(dbContext, command, cancellationToken); if (student != null) { dbContext.RemoveRange(student.Contacts); student.Update( command.NewFirstName, command.NewLastName, command.NewStudentNumber, await GetClassroomAsync(dbContext, command, cancellationToken), command.Contacts?.Select(c => c.ToDomainModel()), command.CitizenshipIdentity, command.NewNotes); dbContext.AttachRange(student.Contacts.Select(c => c.ContactType)); await dbContext.SaveChangesAsync(cancellationToken); await PublishEventAsync(command, cancellationToken); } } return(await base.HandleAsync(command, cancellationToken)); }
public override async Task <AddSmsCreditsCommand> HandleAsync( AddSmsCreditsCommand command, CancellationToken cancellationToken = default) { await using (var dbContext = _dbContextFactory.Create(command.UserId)) { var user = await dbContext.Users .FirstAsync( u => u.Id == command.UserId, cancellationToken); user.AddSmsBalance(command.Amount); await dbContext.SaveChangesAsync(cancellationToken); await _bus.Publish( new SmsCreditAdded( command.Amount, user.SmsBalance, user.FirstName.Value, user.LastName.Value, user.Email, user.Phone, command.Gift, (int)user.Id, user.SubjectId), cancellationToken); } return(await base.HandleAsync(command, cancellationToken)); }
public override async Task <CreateExamCommand> HandleAsync( CreateExamCommand command, CancellationToken cancellationToken = default) { await EnsureNotExistsAsync(command, cancellationToken); Exam exam = null; await using (var dbContext = _dbContextFactory.Create(command.UserId)) { exam = new Exam( command.Name, command.ExamDate, await dbContext.ExamTypes.FirstAsync(e => e.Id == command.ExamTypeId, cancellationToken), Enumeration.GetAll <ExamBookletType>().First(e => e.Id == command.ExamBookletTypeId), command.IncorrectEliminationRate, Enumeration.GetAll <AnswerFormFormat>().First(a => a.Id == command.AnswerFormFormat), await GetLessonAsync(dbContext, command.LessonId), command.ApplicableFormTypeCode, command.Notes, command.Shared); dbContext.Attach(exam.ExamBookletType); dbContext.Attach(exam.AnswerFormFormat); dbContext.Exams.Add(exam); await dbContext.SaveChangesAsync(cancellationToken); } await PublishEventAsync(exam, command.AnswerKeyOpticalForms, cancellationToken); return(await base.HandleAsync(command, cancellationToken)); }
public override async Task <BulkEditContactsCommand> HandleAsync( BulkEditContactsCommand command, CancellationToken cancellationToken = default) { var contactTypes = Domain.SeedWork.Enumeration.GetAll <ContactType>(); await using (var dbContext = _dbContextFactory.Create(command.UserId)) { foreach (var subCommand in command.Commands) { var contact = await dbContext.Contacts .FirstAsync(c => c.Id == subCommand.ContactId, cancellationToken); contact.Update( subCommand.FirstName, subCommand.LastName, subCommand.Phone, contactTypes.First(t => t.Id == subCommand.ContactType), subCommand.Labels); } dbContext.AttachRange(contactTypes); await dbContext.SaveChangesAsync(cancellationToken); } return(await base.HandleAsync(command, cancellationToken)); }
private async Task UpdateWebApiUserAsync(UpdateUserByAdminCommand command, CancellationToken cancellationToken) { await using var dbContext = _dbContextFactory.Create(command.UserId); var user = await GetUserAsync(dbContext, command.UpdatedUserId, cancellationToken); user.Update(command.Email, command.FirstName, command.LastName, command.CityId, command.DistrictId, command.SchoolName, command.MobilePhone, command.Referrer, command.Notes); await dbContext.SaveChangesAsync(cancellationToken); }
public async Task <IActionResult> GetCustomer([FromRoute] int id, CancellationToken cancellationToken) { using (var context = dbContextFactory.Create()) { var customer = await context.DbSet <Customer>() .FirstOrDefaultAsync(x => x.Id == id, cancellationToken); if (customer == null) { return(NotFound()); } var dtoCustomer = Converter.Convert(customer); return(Ok(dtoCustomer)); } }
public async Task <Customer> GetCustomerByEmail(string emailId) { using (var context = dbContextFactory.Create()) { var customers = await context.DbSet <Customer>() .FirstOrDefaultAsync(x => x.Email == emailId); return(customers); } }
public async Task <Response> Create(TeacherCreateModel TeacherCreateModel, ClaimsPrincipal User) { using (var context = _applicationDbContextFactory.Create()) { var user = await _userManager.FindByNameAsync(User.Identity.Name); var Teacher = Mapper.Map <Teacher>(TeacherCreateModel); if (!context.Check <City>(Teacher.CityId)) { return new Response { Status = 500, Message = "Такого города нет" } } ; if (!context.Check <Course>(Teacher.CourseId)) { return new Response { Status = 500, Message = "Такого курса нет" } } ; var Result = context.Teachers.Add(Teacher); context.SaveChanges(); context.TeacherHistories.Add(new TeacherHistory { Action = "Создание", TeacherId = Result.Entity.Id, DateTime = DateTime.Now, UserId = user.Id }); context.SaveChanges(); return(new Response { Status = 100, Message = "Запрос успешно прошел" }); } }
public IReadOnlyCollection <Group> GetAllGroups() { using (var context = _contextFactory.Create(QueryTrackingBehavior.NoTracking)) { return(_groupRepo .FetchAll(context) .ToArray()); } }
public async Task SubscribeAsync(ApplicationUser user, Topic topic, CancellationToken cancellationToken = default(CancellationToken)) { using (var context = factory.Create()) { var registrationTokens = await context.DbSet <UserRegistration>() .Where(x => x.User == user) .Where(x => x.DeactivationDate == null) .Select(x => x.RegistrationToken) .ToArrayAsync(cancellationToken); var topicManagementRequest = new TopicManagementRequest { Topic = topic.Name, RegistrationTokens = registrationTokens }; await client.SubscribeToTopic(topicManagementRequest, cancellationToken); } }
public async Task <Response> Archive(int UserId) { using (var context = applicationDbContextFactory.Create()) { var User = context.Users.Where(i => i.Id == UserId).FirstOrDefault(); if (User == null) { return new Response { Message = "Нет такого пользователя", Status = 500 } } ; User.IsArchive = true; context.Users.Update(User); return(new Response { Message = "Запрос прошел успешно", Status = 100 }); } }
public IQueryable <TEntity> FetchAll(IApplicationDbContext context = null) { if (context != null) { return(context.Set <TEntity>()); } using (var newContext = _contextFactory.Create()) { return(newContext.Set <TEntity>() .AsNoTracking()); } }
//Task<List<HistoryIndexModel> public async Task <List <HistoryIndexModel> > GetAll() { using (var context = _applicationDbContextFactory.Create()) { var Models = new List <HistoryIndexModel>(); var Histories = context.Histories.ToList(); foreach (var History in Histories) { if (History is StudentHistory) { var Student = context.Students.Where(i => i.Id == ((StudentHistory)History).StudentId).FirstOrDefault(); var Model = new HistoryIndexModel { Action = History.Action, DateTime = History.DateTime, Information = Student.Surname + " " + Student.Name + " " + Student.MiddleName, Type = "Студент" }; Models.Add(Model); } if (History is LeadHistory) { var Student = context.Leads.Where(i => i.Id == ((LeadHistory)History).LeadId).FirstOrDefault(); var Model = new HistoryIndexModel { Action = History.Action, DateTime = History.DateTime, Information = Student.Surname + " " + Student.Name + " " + Student.MiddleName, Type = "Лид" }; Models.Add(Model); } if (History is CourseHistory) { var Student = context.Courses.Where(i => i.Id == ((CourseHistory)History).CourseId).FirstOrDefault(); var Model = new HistoryIndexModel { Action = History.Action, DateTime = History.DateTime, Information = Student.Name, Type = "Курсы" }; Models.Add(Model); } if (History is TeacherHistory) { var Student = context.Teachers.Where(i => i.Id == ((TeacherHistory)History).TeacherId).FirstOrDefault(); var Model = new HistoryIndexModel { Action = History.Action, DateTime = History.DateTime, Information = Student.Surname + " " + Student.Name + " " + Student.MiddleName, Type = "Учитель" }; Models.Add(Model); } if (History is GroupHistory) { var Student = context.Groups.Where(i => i.Id == ((GroupHistory)History).GroupId).FirstOrDefault(); var Model = new HistoryIndexModel { Action = History.Action, DateTime = History.DateTime, Information = Student.Name, Type = "Группа" }; Models.Add(Model); } } return(Models); } }
public async Task <Response> Create(GroupCreateModel GroupCreateModel, ClaimsPrincipal user) { using (var context = _applicationDbContextFactory.Create()) { var User = await _userManager.FindByNameAsync(user.Identity.Name); var Group = Mapper.Map <Group>(GroupCreateModel); if (context.Groups.Any(i => i.Name == Group.Name)) { return new Response { Status = 500, Message = "Такая группа уже существует!" } } ; if (!context.Check <Group>(Group.TeacherId)) { return new Response { Status = 500, Message = "Такого учителя нет!" } } ; var Result = context.Groups.Add(Group); context.SaveChanges(); context.groupHistories.Add(new GroupHistory { Action = "Создание", DateTime = DateTime.Now, GroupId = Result.Entity.Id, UserId = User.Id }); context.SaveChanges(); return(new Response { Status = 100, Message = "Запрос успешно прошел" }); } }