using Microsoft.EntityFrameworkCore; namespace samusev_42 { public partial class Form1 : Form { Ispr2522SamusevOvLazarev2Context context; public Form1() { InitializeComponent(); /// при создании записи - она не начинается с 0 и не ломается dataGridView1.AllowUserToAddRows = false; dataGridView1.DataError += (s, e) => { MessageBox.Show("Ошибка формата данных! Проверьте, что в числовые поля не введены буквы.", "Ошибка ввода", MessageBoxButtons.OK, MessageBoxIcon.Warning); e.ThrowException = false; }; dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); context = new Ispr2522SamusevOvLazarev2Context(); context.Products.Include(x => x.IdCategoryNavigation).Load(); context.Products.Include(x => x.IdManufacturerNavigation).Load(); context.Products.Include(x => x.IdProductNameNavigation).Load(); context.Products.Include(x => x.IdSupplierNavigation).Load(); context.Categories.Load(); context.Manufacturers.Load(); context.Database.EnsureCreated(); bindingSource1.DataSource = context.Products.Local.ToBindingList(); categorySource.DataSource = context.Categories.Local.ToBindingList(); manufacturerSource.DataSource = context.Manufacturers.Local.ToBindingList(); product_nameSource.DataSource = context.ProductNames.Local.ToBindingList(); SupplierSource.DataSource = context.Suppliers.Local.ToBindingList(); } private void button1_Click(object sender, EventArgs e) { context.SaveChanges(); dataGridView1.Refresh(); } private void button2_Click(object sender, EventArgs e) { if (bindingSource1.Current == null) return; var form = new EditForm(); form.categoryBindingSource.DataSource = categorySource.DataSource; form.manufacturerBindingSource.DataSource = manufacturerSource.DataSource; form.productNameBindingSource.DataSource = product_nameSource.DataSource; form.supplierBindingSource.DataSource = SupplierSource.DataSource; form.productBindingSource.DataSource = bindingSource1.Current; if (form.ShowDialog() == DialogResult.OK) { bindingSource1.EndEdit(); context.SaveChanges(); dataGridView1.Refresh(); } } private void SaveEditButton_Click(object sender, EventArgs e) { context.SaveChanges(); dataGridView1.Refresh(); } private void buttonDelete_Click(object sender, EventArgs e) { bindingSource1.RemoveCurrent(); context.SaveChanges(); dataGridView1.Refresh(); } /// валидация + заполнение комбобоксов и текстбоксов чтобы не было ошибки null private void buttonAdd_Click_1(object sender, EventArgs e) { var newProduct = new Product(); newProduct.Article = ""; newProduct.Unit = "шт."; newProduct.Description = "-"; newProduct.Photo = ""; newProduct.Price = 0; newProduct.Count = 0; newProduct.Discount = 0; var form = new EditForm(); form.categoryBindingSource.DataSource = categorySource; form.manufacturerBindingSource.DataSource = manufacturerSource; form.productNameBindingSource.DataSource = product_nameSource; form.supplierBindingSource.DataSource = SupplierSource; form.productBindingSource.DataSource = newProduct; if (form.ShowDialog() == DialogResult.OK) { try { if (newProduct.IdProductName <= 0) throw new System.ComponentModel.DataAnnotations.ValidationException("Выберите название товара!"); if (string.IsNullOrWhiteSpace(newProduct.Article)) throw new System.ComponentModel.DataAnnotations.ValidationException("Артикул не может быть пустым!"); if (newProduct.Price < 0) throw new System.ComponentModel.DataAnnotations.ValidationException("Цена не может быть отрицательной!"); context.Products.Add(newProduct); context.SaveChanges(); bindingSource1.DataSource = context.Products.Local.ToBindingList(); dataGridView1.Refresh(); MessageBox.Show("Данные успешно сохранены в базу!"); } catch (System.ComponentModel.DataAnnotations.ValidationException valEx) { MessageBox.Show(valEx.Message, "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (Exception ex) { string inner = ex.InnerException?.Message ?? ex.Message; MessageBox.Show($"Ошибка БД: {inner}"); context.Entry(newProduct).State = EntityState.Detached; } } } } }