private void InitContext() { var builder = new DbContextOptionsBuilder <BooksContext>() .UseInMemoryDatabase("BooksDB"); var context = new BooksContext(builder.Options); var books = Enumerable.Range(1, 10) .Select(i => new Book { BookId = i, Title = $"Sample{i}", Publisher = "Wrox Press" }); context.Books.AddRange(books); int changed = context.SaveChanges(); _booksContext = context; }
public async Task <IActionResult> Create(ArticleModel model, IFormFile file) { if (!ModelState.IsValid) { } var path = "/ArticleCovers/" + file.FileName; using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create)) { await file.CopyToAsync(fileStream); } model.CoverPath = path; db.Articles.Add(model); db.SaveChanges(); return(RedirectToAction("Index")); }
public static void PopulateDatabase() { using var context = new BooksContext(quiet: true); context.AddRange( new User { PhoneNumber = 4255551234, Username = "******" }, new User { PhoneNumber = 5155552234, Username = "******" }, new User { PhoneNumber = 18005525123, Username = "******" }); context.SaveChanges(); }
private static void AddAuthor() { Console.WriteLine("Agregando un autor."); Console.Write("Nombres: "); string firstName = Console.ReadLine(); Console.Write("Apellidos: "); string lastName = Console.ReadLine(); var author = new BooksApp.Data.Author { FirstName = firstName, LastName = lastName }; context.Authors.Add(author); context.SaveChanges(); }
public ActionResult Create(Editora ed) { //Valido que el registro es valido if (ModelState.IsValid) { //Añado el registro a las editoras disponibles db.Editoras.Add(ed); //Guardo los cambios en la base de datos db.SaveChanges(); //Enviame a la pagina de inicio return(RedirectToAction("Index")); } else { //Si paso algun error, vuelve a la pagina con la informacion del registro para que la comprueben return(View(ed)); } }
public async Task <IActionResult> Create(BookModel model, IFormFile file) { if (!ModelState.IsValid) { return(this.View()); } var path = "/img/BookCovers/" + file.FileName; using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create)) { await file.CopyToAsync(fileStream); } model.CoverPath = "~/img/BookCovers/" + file.FileName; db.Books.Add(model); db.SaveChanges(); return(this.RedirectToAction("Index")); }
public ActionResult Create(CreateAutoresVM _viewModel) { //Chequeamos el estado del modelo if (ModelState.IsValid) { //Agregamos el registro a los autores existentes db.Autores.Add(_viewModel._autor); //Guardamos los datos db.SaveChanges(); //Mandamos al usuario a la lista return(RedirectToAction("Index")); } else { //Si algo salio mal, lo devolvemos return(View(_viewModel)); } }
public Author CreateAuthor([Service] BooksContext context, AuthorAndBook authorAndBook) { var author = new Author() { Name = authorAndBook.AuthorName, Books = new List <Book> { new Book { Title = authorAndBook.Title } } }; context.Authors.Add(author); context.SaveChanges(); return(author); }
public static void Initialize(BooksContext context) { if (!context.Books.Any()) { context.Books.AddRange( new Book { name = "Цивилизация с нуля", pages = 150, price = 150.5, image = "testImage", author = "testAuthor", kolvo = 10, publisher = new Publisher("firstPublisher"), category = new Category("Художественная литература") }, new Book { name = "Spring in Action", pages = 1500, price = 1500.5, image = "testImage2", author = "testAuthor2", kolvo = 10, publisher = new Publisher("secondPublisher"), category = new Category("Учебная литература") }, new Book { name = "Энциклопедия", pages = 120, price = 1240.5, image = "testImage3", author = "testAuthor3", kolvo = 10, publisher = new Publisher("thirdPublisher"), category = new Category("Справочник") } ); context.SaveChanges(); } }
public static void PopulateDatabase() { using var context = new BooksContext(quiet: true); context.AddRange( new Shard { Token1 = "A", Token2 = "B", Token3 = "C", TokensProcessed = "ABC" }, new Shard { Token1 = "D", Token2 = "H", Token3 = "C", TokensProcessed = "DH" }, new Shard { Token1 = "A", Token2 = "B", Token3 = "C" }, new Shard { Token1 = "D", Token2 = "E", Token3 = "F", TokensProcessed = "DEF" }, new Shard { Token1 = "J", Token2 = "A", Token3 = "M", TokensProcessed = "JAM" }); context.SaveChanges(); }
public Author CreateAuthorWithArgumentDescription([Service] BooksContext context, [GraphQLDescription("Argument description: Author with a book description")] AuthorAndBook authorAndBook) { var author = new Author() { Name = authorAndBook.AuthorName, Books = new List <Book> { new Book { Title = authorAndBook.Title } } }; context.Authors.Add(author); context.SaveChanges(); return(author); }
public void UpdateCover(Book book) { using (var ctx = new BooksContext()) { var updateBook = ctx.Books .Include(x => x.Covers) .First(x => x.Id == book.Id); var newCovers = book.Covers.Where(x => !updateBook.Covers.Any(y => y.FilePath == x.FilePath)); foreach (var cover in newCovers) { updateBook.Covers.Add(new Cover { FilePath = cover.FilePath }); } ctx.SaveChanges(); } }
private User FindUserOrAdd(Google.Apis.Auth.GoogleJsonWebSignature.Payload payload) { var u = _context.Users.Where(x => x.Email == payload.Email).FirstOrDefault(); if (u == null) { u = new User() { UserId = Guid.NewGuid(), Name = payload.Name, Picture = payload.Picture, Email = payload.Email, oauthSubject = payload.Subject, oauthIssuer = payload.Issuer, }; _context.Users.Add(u); _context.SaveChanges(); } return(u); }
static void Main(string[] args) { var booksContext = new BooksContext(); booksContext.Add(new Book() { Title = "Mein erstes Buch", BookId = 1, Publisher = "Selbstpublizierer" }); booksContext.Add(new Book() { Title = "Mein zweites Buch", BookId = 2, Publisher = "Pakito" }); booksContext.Add(new Book() { Title = "Mein drittes Buch", BookId = 3, Publisher = "Pako" }); booksContext.Add(new Book() { Title = "Mein viertes Buch", BookId = 4, Publisher = "Selbstpublizierer" }); booksContext.SaveChanges(); }
// Register button logic private void registerButton_Click(object sender, EventArgs e) { if (context.Readers.ToList().Where(r => r.nickname == nicknameTextBox.Text).Count() == 0) // Сheck nick's uniqueness { if (passwordTextBox.Text.Equals(confirmPasswordTextBox.Text)) // Check the password { // Creating a new user Reader reader = new Reader(); reader.name = nameTextBox.Text; reader.nickname = nicknameTextBox.Text; reader.password = PasswordManager.HashPassword(passwordTextBox.Text); reader.spentPoints = 0; reader.receivedPoints = 0; using (var ctx = new BooksContext()) { ctx.Readers.Add(reader); ctx.SaveChanges(); } // Open Main Form MessageBox.Show("User was successfully created", "Congrats"); LoginForm loginForm = new LoginForm(); loginForm.Show(); Hide(); } else // If passwords dont match { MessageBox.Show("Passwords don't match", "Pay attention"); passwordTextBox.Text = ""; confirmPasswordTextBox.Text = ""; } } else // If user already exists { MessageBox.Show("User already exists", "Something went wrong :c"); } }
public void DbEntityValidationException() { DoTest(DbEntityValidationExceptionExpectation, () => { using (var dbContext = new BooksContext()) { dbContext.Books.Add(new Book { Id = Guid.Parse("240B10F4-11DC-4E75-B268-DA922FA6D781"), Name = "Foo" }); try { dbContext.SaveChanges(); } catch (DbEntityValidationException ex) { return(ex); } } Assert.Fail(); return(null); }); }
public void IncCountBooks(Book book) { book.Count++; _context.Update(book); _context.SaveChanges(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BooksContext db) { if (db.Database.EnsureCreated()) { db.Authors.Add(new Author { Name = "Jane Austen", DateOfBirth = new DateTime(1775, 12, 16), Books = new List <Book> { new Book { Title = "Emma", YearOfPublication = 1815 }, new Book { Title = "Persuasion", YearOfPublication = 1818 }, new Book { Title = "Mansfield Park", YearOfPublication = 1814 } } }); db.Authors.Add(new Author { Name = "Ian Fleming", DateOfBirth = new DateTime(1908, 5, 28), Books = new List <Book> { new Book { Title = "Dr No", YearOfPublication = 1958 }, new Book { Title = "Goldfinger", YearOfPublication = 1959 }, new Book { Title = "From Russia with Love", YearOfPublication = 1957 } } }); db.Authors.Add(new Author { Name = "George Eliot", DateOfBirth = new DateTime(1819, 11, 22), Books = new List <Book> { new Book { Title = "Silas Marner", YearOfPublication = 1815 }, new Book { Title = "Middlemarch", YearOfPublication = 1871 } } }); db.SaveChanges(); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Books}/{action=Index}/{id?}"); }); }
public void AddElem(Genre elem) { _context.Genres.Add(elem); _context.SaveChanges(); }
public void Create(Book book) { db.Books.Add(book); db.SaveChanges(); }
public void AddMenuElement(MenuElement elem) { _context.MenuElements.Add(elem); _context.SaveChanges(); }
public void Save() { _context.SaveChanges(); }
public void AddBook(Book book) { _booksContext.Books.Add(book); _booksContext.SaveChanges(); }
public Book CreateBook(Book createdBook) { _context.Books.Add(createdBook); _context.SaveChanges(); return(createdBook); }
public void AddElem(Book elem) { _context.Books.Add(elem); _context.SaveChanges(); }
public Book AddBook(Book book) { _booksContext.Books.Add(book); _booksContext.SaveChanges(); return(book); }
public void Save() { booksContext.SaveChanges(); }
public ActionResult PostCategory(Category category) { _booksContext.Categories.Add(category); _booksContext.SaveChanges(); return(Ok("added")); }
public void Save() { db.SaveChanges(); }
public void Post([FromBody] Book value) { _booksContext.Books.Add(value); _booksContext.SaveChanges(); }