private void Button_Click(object sender, RoutedEventArgs e) { try// на случай пустой или битой строки { if (dataGrid2.SelectedItem != null) { var selectedBook = (Book)dataGrid2.SelectedItem; var tempBook = new BookOrganizer.Book() { Title = selectedBook.Name, Annotation = selectedBook.Annotation, Author = new Author() { Name = selectedBook.Author }, Year = int.Parse(selectedBook.Year), Pages = int.Parse(selectedBook.Pages) }; var v = new AddBookView(); v.DataContext = new AddBookViewModel(tempBook); ((AddBookViewModel)v.DataContext).BookOut += (b) => { using (var c = new Context()) { if (b.Author != null) { var k = c.Authors.FirstOrDefault(p => p.Name == b.Author.Name); if (k != null) { b.Author = k; } } if (b.Genre != null) { var t = c.Genres.FirstOrDefault(p => p.Name == b.Genre.Name); if (t != null) { b.Genre = t; } } c.Books.Add(b); c.SaveChanges(); } v.Close(); }; v.Show(); } } catch { } }
private void EditBook() { if (selectedBook != null) { var id = selectedBook.Id; using (var c = new Context()) { var bookForEdit = c.Books.Include("Author").Include("Genre").First(p => p.Id == id); object old = bookForEdit.Clone(); var v = new AddBookView(); v.DataContext = new AddBookViewModel(bookForEdit); ((AddBookViewModel)v.DataContext).BookOut += (b) => { using (var t = new Context()) { var temp = t.Books.Include("Author").Include("Genre").First(p => p.Id == id); temp.PullChanges(b); temp.Author = t.Authors.FirstOrDefault(p => p.Id == temp.Author.Id); temp.Genre = t.Genres.FirstOrDefault(p => p.Id == temp.Genre.Id); t.SaveChanges(); } Undos.Push(new object[] { "unedit", (Book)old }); OnPropertyChanged("UndoIsEnabled"); OpenList(selectedMode); v.Close(); }; v.ShowDialog(); } } }
private void AddBook() { var v = new AddBookView(); v.DataContext = new AddBookViewModel(new Book()); ((AddBookViewModel)v.DataContext).BookOut += (b) => { AddBookToDB(b); using (var c = new Context()) { Undos.Push(new object[] { "delete", c.Books.Include("Author").Include("Genre").First(p => p.Author.Name == b.Author.Name && p.Year == b.Year && p.Title == b.Title) }); OnPropertyChanged("UndoIsEnabled"); } OpenList(selectedMode); v.Close(); }; v.ShowDialog(); }