public HomeController() { var connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; var context = new LocalDatabaseContext(connectionString); repository = new DatabaseBlogPostRepository(context); }
public void CompareTest() { DbContextOptions <LocalDatabaseContext> options = new DbContextOptionsBuilder <LocalDatabaseContext>() .UseInMemoryDatabase("DatabaseTestName") .Options; using (var context = new LocalDatabaseContext(options)) { var schedule = new ScheduleDbRecord { GroupName = "test_name", JsonScheduleData = "other data" }; context.ScheduleDbRecords.Add(schedule); context.SaveChanges(); } using (var context = new LocalDatabaseContext(options)) { int count = context.ScheduleDbRecords.Count(); Assert.AreEqual(1, count); ScheduleDbRecord u = context .ScheduleDbRecords .FirstOrDefault(user => user.GroupName == "test_name" && user.JsonScheduleData == "other data"); Assert.IsNotNull(u); } }
public DatabaseBlogPostRepository(LocalDatabaseContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } this.context = context; }
public static async Task <bool> DeleteAsync(Asd_E_Type type, Guid id, string correlationId) { // информация для логирования var preLog = correlationId + " | " + ClassName + "." + type + "." + ExtensionProvider.GetCallerMethodName(); // логируем начало выполнения метода Logging.Trace(preLog + " START"); // выполнение метода try { // логируем запрос Logging.Request(preLog + "(Запрос метода. Исходные данные: Id = " + id + ")"); // создаем объект ответа bool response; // удаляем данные из базы данных await using (var context = new LocalDatabaseContext()) { switch (type) { case Asd_E_Type.Employee: var employee = await context.Employees.FindAsync(id); context.Employees.Remove(employee); response = await context.SaveChangesAsync() > 0; break; case Asd_E_Type.Department: var department = await context.Departments.FindAsync(id); context.Departments.Remove(department); response = await context.SaveChangesAsync() > 0; break; default: response = false; break; } } // логируем ответ Logging.Response(preLog + "(Ответ метода: " + response + ")"); // возвращаем ответ return(response); } catch (Exception ex) { // логируем исключение Logging.Exception(preLog + "(" + ex.Message + ")" + ex.StackTrace.ToTabString()); // возвращаем ответ return(false); } finally { // логируем окончание выполнения метода Logging.Trace(preLog + " END"); } }
static void Main(string[] args) { String connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Development\Playground\Lecture02.BlogPosts.EntityFramework\Lecture02.BlogPosts.EntityFramework\BlogDatabase.mdf;Integrated Security=True;MultipleActiveResultSets=True"; using (var context = new LocalDatabaseContext(connectionString)) { AddTestData(context); WriteBlogPosts(context); } }
private static void WriteBlogPosts(LocalDatabaseContext context) { foreach (var blogPost in context.BlogPosts.ToArray()) { Console.WriteLine(blogPost); foreach (var author in blogPost.Authors.ToArray()) { Console.WriteLine(author); } } Console.ReadKey(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); var context = new LocalDatabaseContext(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BLOGDATABASE_25f1476eeb6f46e5b0cd8c7e02644db2;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); var blogPostRepository = new DatabaseBlogPostRepository(context); var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>()) { PasswordValidator = new MinimumLengthValidator(4) }; ControllerBuilder.Current.SetControllerFactory(new StandardControllerFactory(blogPostRepository, userManager)); }
public static async Task <bool> FindAsync(Asd_E_Type type, Guid id, string correlationId) { // информация для логирования var preLog = correlationId + " | " + ClassName + "." + type + "." + ExtensionProvider.GetCallerMethodName(); // логируем начало выполнения метода Logging.Trace(preLog + " START"); // выполнение метода try { // логируем запрос Logging.Request(preLog + "(Запрос метода. Исходные данные: Id = " + id + ")"); // создаем объект ответа bool response; // получаем данные из базы данных await using (var context = new LocalDatabaseContext()) { response = type switch { Asd_E_Type.Employee => await context.Employees.FindAsync(id) != null, Asd_E_Type.Department => await context.Departments.FindAsync(id) != null, _ => false }; } // логируем ответ Logging.Response(preLog + "(Ответ метода: " + response + ")"); // возвращаем ответ return(response); } catch (Exception ex) { // логируем исключение Logging.Exception(preLog + "(" + ex.Message + ")" + ex.StackTrace.ToTabString()); // возвращаем ответ return(false); } finally { // логируем окончание выполнения метода Logging.Trace(preLog + " END"); } }
private static void AddTestData(LocalDatabaseContext context) { var blogPost = new BlogPost { Title = "Test", Content = "Lorem ipsum", CreatedDate = DateTime.Now, }; var johnDoeAuthor = new Author { FullName = "John Doe", BlogPosts = new[] { blogPost } }; context.Authors.Add(johnDoeAuthor); context.BlogPosts.Add(blogPost); context.SaveChanges(); }
public static async Task <bool> PutAsync <T>(Asd_E_Type type, Guid id, T request, string correlationId) { // информация для логирования var preLog = correlationId + " | " + ClassName + "." + type + "." + ExtensionProvider.GetCallerMethodName(); // логируем начало выполнения метода Logging.Trace(preLog + " START"); // выполнение метода try { // логируем запрос Logging.Request(preLog + "(Запрос метода. Исходные данные: Id = " + id + ")" + JsonConvert.SerializeObject(request, Formatting.Indented).ToTabString()); // создаем объект ответа bool response; // обновляем данные в базе данных await using (var context = new LocalDatabaseContext()) { context.Entry(request).State = EntityState.Modified; response = await context.SaveChangesAsync() > 0; } // логируем ответ Logging.Response(preLog + "(Ответ метода: " + response + ")"); // возвращаем ответ return(response); } catch (Exception ex) { // логируем исключение Logging.Exception(preLog + "(" + ex.Message + ")" + ex.StackTrace.ToTabString()); // возвращаем ответ return(false); } finally { // логируем окончание выполнения метода Logging.Trace(preLog + " END"); } }
public StationRepository(LocalDatabaseContext context) { _context = context; }
public GenericDatabaseRepository(LocalDatabaseContext context) { _context = context; }
internal static bool TryCreateNewDatabase() { using var dbContext = new LocalDatabaseContext(); return(dbContext.Database.EnsureCreated()); }
public static async Task <object> GetAsync(Asd_E_Type type, string correlationId) { // информация для логирования var preLog = correlationId + " | " + ClassName + "." + type + "." + ExtensionProvider.GetCallerMethodName(); // логируем начало выполнения метода Logging.Trace(preLog + " START"); // выполнение метода try { // логируем запрос Logging.Request(preLog + "(Запрос метода.)"); // создаем объект ответа IEnumerable <object> response; // получаем данные из базы данных await using (var context = new LocalDatabaseContext()) { response = type switch { Asd_E_Type.Employee => await context.Employees .Select(i => new { i.Id, i.Name, Department = new { i.Department.Id, i.Department.Name } }).ToListAsync(), Asd_E_Type.Department => await context.Departments .Include(i => i.Employees) .Select(i => new { i.Id, i.Name, i.Employees.Count, Avg = i.Employees.Sum(j => j.Salary) / i.Employees.Count, Employees = i.Employees .Select(j => new { j.Id, j.Name, j.Salary }) }).ToListAsync(), _ => null }; } // логируем ответ Logging.Response(preLog + "(Ответ метода.)" + JsonConvert.SerializeObject(response, Formatting.Indented).ToTabString()); // возвращаем ответ return(response); } catch (Exception ex) { // логируем исключение Logging.Exception(preLog + "(" + ex.Message + ")" + ex.StackTrace.ToTabString()); // возвращаем ответ return(null); } finally { // логируем окончание выполнения метода Logging.Trace(preLog + " END"); } }
public static void CreateTestDatabaseWithFixedTime(DateTime now) { using var dbContext = new LocalDatabaseContext(); bool newCreated = dbContext.Database.EnsureCreated(); if (!newCreated) { Debug.WriteLine(@"Error: Database not created!"); return; } dbContext.Persons.AddRange( new Person { FirstName = "Kamila", LastName = "Spoustová", Address = null }, new Person { FirstName = "Naděžda", LastName = "Pavelková", Address = null }, new Person { FirstName = "Silvie", LastName = "Hronová", Address = null, Id = 3 }, new Person { FirstName = "Miloš", LastName = "Korbel", Address = null }, new Person { FirstName = "Petr", LastName = "Hrubec", Address = null, Id = 5 }, new Person { FirstName = "Michal", LastName = "Vyvlečka", Address = null }, new Person { Id = 12, FirstName = "Lenka", LastName = "Kiasová", Address = new Address { City = null, Country = null, PostalCode = null, Street = null } }); dbContext.ClubAirplanes.AddRange( new ClubAirplane { Id = 2, Immatriculation = "OK-B123", AirplaneType = new AirplaneType { Type = "L-13A Blaník" } }, new ClubAirplane { Id = 1, Immatriculation = "OK-V23424", AirplaneType = new AirplaneType { Type = "Zlín Z-42M" } }); dbContext.Airplanes.AddRange( new Airplane { Id = 2, GuestAirplaneImmatriculation = "OK-B123", GuestAirplaneType = "L-13A Blaník" }, new Airplane { Id = 1, GuestAirplaneImmatriculation = "OK-V23424", GuestAirplaneType = "Zlín Z-42M" }); dbContext.Flights.AddRange( new Flight { Id = 1, TakeoffTime = now.AddMinutes(-10), LandingTime = null, Airplane = dbContext.Airplanes.Find(1L), Pilot = dbContext.Persons.Find(12L), Copilot = null, Task = "VLEK", Type = FlightType.Glider }, new Flight { Id = 4, TakeoffTime = now.AddMinutes(-10), LandingTime = null, Airplane = dbContext.Airplanes.Find(2L), Pilot = dbContext.Persons.Find(3L), Copilot = null, Task = "Tahac", Type = FlightType.Towplane }, new Flight { Id = 24057, TakeoffTime = now.AddMinutes(-100), LandingTime = null, Airplane = dbContext.Airplanes.Find(1L), Pilot = dbContext.Persons.Find(5L), Copilot = null, Task = "VLEK", Type = FlightType.Glider }, new Flight { Id = 24058, TakeoffTime = now.AddMinutes(-100), LandingTime = null, Airplane = dbContext.Airplanes.Find(2L), Pilot = dbContext.Persons.Find(3L), Copilot = null, Task = "Tahac", Type = FlightType.Towplane }, new Flight { Id = 444, TakeoffTime = new DateTime(2020, 1, 7, 16, 47, 10), LandingTime = new DateTime(2020, 1, 7, 17, 17, 10), Airplane = dbContext.Airplanes.Find(2L), Pilot = dbContext.Persons.Find(12L), Copilot = null, Task = "Tahac", Type = FlightType.Towplane }); dbContext.FlightStarts.AddRange( new FlightStart { Glider = dbContext.Flights.Find(1L), Towplane = dbContext.Flights.Find(4L) }, new FlightStart { Glider = dbContext.Flights.Find(24057L), Towplane = dbContext.Flights.Find(24058L) }, new FlightStart { Towplane = dbContext.Flights.Find(444L) }); dbContext.SaveChanges(); }
public static void DeleteOldDatabase() { using var dbContext = new LocalDatabaseContext(); dbContext.Database.EnsureDeleted(); }
public static async Task <Guid?> PostAsync <T>(Asd_E_Type type, T request, string correlationId) { // информация для логирования var preLog = correlationId + " | " + ClassName + "." + type + "." + ExtensionProvider.GetCallerMethodName(); // логируем начало выполнения метода Logging.Trace(preLog + " START"); // выполнение метода try { // логируем запрос Logging.Request(preLog + "(Запрос метода. Исходные данные.)" + JsonConvert.SerializeObject(request, Formatting.Indented).ToTabString()); // создаем объект ответа Guid response; // добавляем данные в базу данных await using (var context = new LocalDatabaseContext()) { switch (type) { case Asd_E_Type.Employee: var employee = request as Employee; await context.Employees.AddAsync(employee ?? throw new InvalidOperationException()); await context.SaveChangesAsync(); response = await context.Employees.Select(i => i.Id).FirstOrDefaultAsync(i => i == employee.Id); break; case Asd_E_Type.Department: var department = request as Department; await context.Departments.AddAsync(department ?? throw new InvalidOperationException()); await context.SaveChangesAsync(); response = await context.Departments.Select(i => i.Id).FirstOrDefaultAsync(i => i == department.Id); break; default: response = Guid.Empty; break; } } // логируем ответ Logging.Response(preLog + "(Ответ метода: Id = " + response + ")"); // возвращаем ответ return(response); } catch (Exception ex) { // логируем исключение Logging.Exception(preLog + "(" + ex.Message + ")" + ex.StackTrace.ToTabString()); // возвращаем ответ return(null); } finally { // логируем окончание выполнения метода Logging.Trace(preLog + " END"); } }
public FavoriteTrainRepository(LocalDatabaseContext context) { _context = context; }
public DefaultController() { var context = new LocalDatabaseContext(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BLOGDATABASE_25f1476eeb6f46e5b0cd8c7e02644db2;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); this.repository = new DatabaseBlogPostRepository(context); }