// SqlConnection m_dbConnection = new SqlConnection(clsThamSoUtilities.connectionString); public DataTable GetAll(string name, string mavattu, string tenvattu, string TenChatLuong) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { var dm = (from d in help.ent.Vat_Tu_Goi_Dau_Ky join e in help.ent.DM_Vat_Tu on d.Ma_vat_tu equals e.Ma_vat_tu join f in help.ent.DM_Kho on d.ID_kho equals f.ID_kho join gl in help.ent.Chat_luong on d.ID_chat_luong equals gl.Id_chat_luong where gl.Loai_chat_luong.Contains(TenChatLuong) && f.Ten_kho.Contains(name)&& e.Ten_vat_tu .Contains(tenvattu) && e.Ma_vat_tu.Contains(mavattu) group d by new { d.Ma_vat_tu, e.Ten_vat_tu , f.Ten_kho,gl.Loai_chat_luong} into gs let TotalPoints = gs.Sum(m => m.So_Luong) orderby TotalPoints descending select new { ten_kho = gs.Key.Ten_kho, Chat_luong = gs.Key.Loai_chat_luong, Ma_vat_tu = gs.Key.Ma_vat_tu, ten_vat_tu = gs.Key.Ten_vat_tu, so_luong = TotalPoints }).ToList(); dbcxtransaction.Commit(); return Utilities.clsThamSoUtilities.ToDataTable(dm); } }
public int Insert() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); // insert using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { try { var t = new User //Make sure you have a table called test in DB { User_name = this.User_name, Password = this.Password, // ID = Guid.NewGuid(), }; help.ent.Users.Add(t); help.ent.SaveChanges(); dbcxtransaction.Commit(); return 1; } catch (Exception ex) { dbcxtransaction.Rollback(); return 0; } } }
// End GetAll /// <summary> /// Kiểm tra trùng lập trước khi ADD /// </summary> /// <returns></returns> public bool Checkduplicaterows() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); bool has = help.ent.DM_Vat_Tu.Any(cus => cus.Ma_vat_tu == Ma_vat_tu); return has; ////Mở //m_dbConnection.Open(); //DataTable dt = new DataTable(); ////Chuẩn bị //string sql = ""; //sql += "SELECT * FROM DM_Vat_Tu "; //sql += "WHERE Ma_vat_tu=@Ma_vat_tu"; //SqlCommand command = new SqlCommand(sql, m_dbConnection); //command.Parameters.Add("@Ma_vat_tu", SqlDbType.Int).Value = Ma_vat_tu; //command.CommandType = CommandType.Text; ////Run //SqlDataAdapter da = new SqlDataAdapter(command); //da.Fill(dt); ////Đóng //m_dbConnection.Close(); //if (dt.Rows.Count > 0) //{ // return true; //} //return false; }
/// <summary> /// hàm tìm kiếm vật tư theo kho và chất lượng /// </summary> /// <param name="_ID_kho"></param> /// <returns></returns> public static DataTable getAll(string TenKho, string TenChatLuong,string tenvt, string mavt) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { var dm = (from d in help.ent.Ton_kho join e in help.ent.DM_Vat_Tu on d.Ma_vat_tu equals e.Ma_vat_tu join f in help.ent.DM_Kho on d.ID_kho equals f.ID_kho join gl in help.ent.Chat_luong on d.Id_chat_luong equals gl.Id_chat_luong where gl.Loai_chat_luong.Contains(TenChatLuong) && f.Ten_kho.Contains(TenKho)&& e.Ten_vat_tu .Contains(tenvt) && e.Ma_vat_tu.Contains(mavt) && (f.isKhoNgoai == false || f.isKhoNgoai ==null) group d by new { d.Ma_vat_tu, e.Ten_vat_tu } into gs let TotalPoints = gs.Sum(m => m.So_luong) orderby TotalPoints descending select new { Ma_vat_tu = gs.Key.Ma_vat_tu, ten_vat_tu = gs.Key.Ten_vat_tu, so_luong = TotalPoints }).ToList(); dbcxtransaction.Commit(); return Utilities.clsThamSoUtilities.ToDataTable(dm); } }
public int Update() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); int temp = 0; using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { Vat_Tu_Goi_Dau_Ky vtgd = new Vat_Tu_Goi_Dau_Ky(); vtgd.ID_kho = this.ID_kho; vtgd.ID_chat_luong= this.ID_chat_luong; vtgd.Ma_vat_tu = this.Ma_vat_tu; vtgd.ID_VT_Goi_Dau = this.ID_VT_Goi_Dau; vtgd.So_Luong = this.So_Luong; using (var context = help.ent) { context.Vat_Tu_Goi_Dau_Ky.Attach(vtgd); context.Entry(vtgd).State = EntityState.Modified; temp = help.ent.SaveChanges(); dbcxtransaction.Commit(); } } return temp; }
public static DataTable GetAll(string name) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { var dm = (from d in help.ent.Kho_muon_vat_tu join k in help.ent.DM_Kho on d.ID_Kho equals k.ID_kho join c in help.ent.Chat_luong on d.Id_chat_luong equals c.Id_chat_luong join v in help.ent.DM_Vat_Tu on d.Ma_vat_tu equals v.Ma_vat_tu where k.Ten_kho .Contains(name) &&d.Da_tra == false select new { ID_kho_muon_vat_tu = d.ID_kho_muon_vat_tu, ID_kho = d.ID_Kho, ID_Kho_Muon = d.ID_Kho_muon, Ma_vat_tu = d.Ma_vat_tu, Ten_vat_tu = v.Ten_vat_tu, So_luong = d.So_luong, Ma_phieu_xuat_tam = d.Ma_phieu_xuat_tam, ID_chat_luong = d.Id_chat_luong, Ten_chat_luong = c.Loai_chat_luong, // Ten_kho = k.Ten_kho, } ).ToList(); dbcxtransaction.Commit(); DataTable ds = Utilities.clsThamSoUtilities.ToDataTable(dm); return ds; } }
public bool CheckTonTaiSoDK() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); bool has = help.ent.Vat_Tu_Goi_Dau_Ky.Any(cus => cus.Ma_vat_tu == Ma_vat_tu && cus.ID_chat_luong ==ID_chat_luong && cus.ID_kho == ID_kho); return has; }
public int Insert() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); // insert using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { try { var t = new Vat_Tu_Goi_Dau_Ky //Make sure you have a table called test in DB { ID_VT_Goi_Dau = this.ID_VT_Goi_Dau, Ma_vat_tu = this.Ma_vat_tu, // ID = Guid.NewGuid(), So_Luong = this.So_Luong, ID_ky = this.ID_ky, ID_chat_luong = this.ID_chat_luong, ID_kho = this.ID_kho, }; help.ent.Vat_Tu_Goi_Dau_Ky.Add(t); help.ent.SaveChanges(); dbcxtransaction.Commit(); return 1; } catch (Exception ex) { dbcxtransaction.Rollback(); return 0; } } }
public bool CheckTonTaiSoDK(string maphieu ,string mavattu, int cl) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); bool has = help.ent.No_vat_tu.Any(cus => cus.Ma_phieu_xuat_tam == maphieu &&cus.Ma_vat_tu == mavattu && cus.Id_chat_luong == cl); return has; }
private void CarregaDados() { // Limpa dataGrid dgridSelMsg.ItemsSource = null; // Tenta try { // Gera novo objeto de conexao ao banco de dados var objDb = new DatabaseHelper("aniversariantes"); // Define SQL Query var query = "SELECT id, c_titulo FROM dados.mensagem WHERE b_deletado <> true"; // Executa a query var dt = objDb.GetDataTable(query); // Seta itens do datagrid com o retorno da query dgridSelMsg.ItemsSource = dt.DefaultView; } // Trata excessão catch (Exception fail) { // Seta mensagem de erro var error = "O seguinte erro ocorreu:\n\n"; // Anexa mensagem de erro na mensagem error += fail.Message + "\n\n"; // Apresenta mensagem na tela MessageBox.Show(error); // Fecha o formulário Close(); } }
public static string RandomMaPhieu() { DateTime today = DateTime.Today; string year = today.ToString("yy"); string month = today.ToString("MM"); string day = today.ToString("dd"); //kiểm tra xem ngày hiện tại có mã số nào chưa ?\ //nếu có thì dd.mm.yy.xx+1 vào //nếu chưa có thì tạo dd.mm.yy.00 DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); var showPiece = (help.ent.Chi_Tiet_Phieu_Xuat_Tam .FirstOrDefault(p => p.Ma_phieu_xuat_tam == help.ent.Chi_Tiet_Phieu_Xuat_Tam.Max(x => x.Ma_phieu_xuat_tam))); if (showPiece != null && showPiece.Ma_phieu_xuat_tam.Contains(day + "." + month + "." + year)) { string[] temp = showPiece.Ma_phieu_xuat_tam.Split('.'); int value = int.Parse(temp[temp.Length]) + 1; return day + month + year + showPiece; } else { // showPiece.Ma_phieu_xuat_tam.Split return (string)(day + "." + month + "." + year + "." + "0000"); } }
public int Insert(DatabaseHelper help) { // insert { try { var t = new The_kho //Make sure you have a table called test in DB { Ma_vat_tu = this.Ma_vat_tu, // ID = Guid.NewGuid(), Id_chat_luong = this.ID_chat_luong, Don_vi = this.Don_vi, Dia_diem = this.Dia_diem, }; help.ent.The_kho.Add(t); help.ent.SaveChanges(); return 1; } catch (Exception ex) { return 0; } } }
public int Insert(DatabaseHelper help) { { try { var t = new Can_tru_no_nhap_ngoai //Make sure you have a table called test in DB { Id_chat_luong = this.Id_chat_luong, Ma_vat_tu = this.Ma_vat_tu, // ID = Guid.NewGuid(), So_luong_can_tru = this.So_luong_can_tru, Ma_phieu_nhap = this.Ma_phieu_nhap, Ma_phieu_nhap_no = this.Ma_phieu_nhap_no, }; help.ent.Can_tru_no_nhap_ngoai.Add(t); help.ent.SaveChanges(); //dbcxtransaction.Commit(); return 1; } catch (Exception ex) { //dbcxtransaction.Rollback(); return 0; } } }
/// <summary> /// Trata da alteração do destino /// </summary> private void AlterarCliente() { // Verifica validação dos dados if (ValidaDados()) { // Cria objeto de acesso ao banco de dados var objAltCliente = new DatabaseHelper(); // Criamos o dicionario de dados com as chaves e valores var dctDados = new Dictionary<string, string>(); // Incluimos no dicionario o campo de destino dctDados.Add("i_cdcliente", tbCpdCli.Text); dctDados.Add("c_nomefantas", tbNomeFantasia.Text); // Valida se consegue inserir informação no banco de dados if (objAltCliente.Update("dados.cliente", dctDados, "id =" + CodID)) { // Mostra mensagem de sucesso MessageBox.Show("Cliente alterado com sucesso"); } else { // Mostra mensagem de erro MessageBox.Show("Ocorreu erro ao tentar alterar o cliente\nContate o seu administrador"); } // Fecha a janela Close(); } }
//public WorkOutManager workOutsource; public MainPage() { this.InitializeComponent(); // CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar; // var currentView = SystemNavigationManager.GetForCurrentView(); //currentView.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; // var deviceFamily = AnalyticsInfo.VersionInfo.DeviceFamily; // if (deviceFamily == "Windows.Desktop") // { // AddCustomTitleBar(); // } // if (deviceFamily == "Windows.Mobile") // { // AlterStatusBar(); // } dbHelper = new DatabaseHelper(App.SQLITE_PLATFORM, App.DB_PATH); //MainView is in the xaml // MainView.ViewModel = new MainPageViewModel(dbHelper); NavigationCacheMode = NavigationCacheMode.Required; RootFrame = frame; }
public CadFuncionario(string operacao, string id) { // Inicializa componentes da janela InitializeComponent(); // Define o tipo de operação com o parametro recebido TipoOperacao = operacao; // Define o id com o parametro recebido CodID = id; if (TipoOperacao == "alterar") { // Atualiza campo ID tbCodigo.Text = CodID; // Cria novo objeto de acesso ao banco de dados var objDB = new DatabaseHelper(); // Define codigo SQL var SQL = string.Format("SELECT c_funcionario FROM dados.funcionario WHERE id = '{0}'", CodID); // Salvo titulo destino na variavel var TituloFuncionario = objDB.ExecuteScalar(SQL); // Atualiza campo nome tbFuncionario.Text = TituloFuncionario; } }
/// <summary> /// Trata da alteração do destino /// </summary> private void AlterarFuncionario() { // Valida se o campo destino está vazio if (string.IsNullOrEmpty(tbFuncionario.Text)) { // Informa ao usuário que é necessário preencher o campo destino MessageBox.Show("Você não preencheu o campo nome"); } // else { // Cria objeto de acesso ao banco de dados var objAltDestino = new DatabaseHelper(); // Criamos o dicionario de dados com as chaves e valores var dctDados = new Dictionary<string, string>(); // Incluimos no dicionario o campo de destino dctDados.Add("c_funcionario", tbFuncionario.Text); // Valida se consegue inserir informação no banco de dados if (objAltDestino.Update("dados.funcionario", dctDados, "id =" + CodID)) { // Mostra mensagem de sucesso MessageBox.Show("Funcionário alterado com sucesso"); } else { // Mostra mensagem de erro MessageBox.Show("Ocorreu erro ao tentar alterar o funcionário\nContate o seu administrador"); } // Fecha a janela Close(); } }
public static DataTable GetAll(string mavt) { // lấy tất cả các phiếu nhập đã xác nhận và loại là hoàn nhập hoac nhap goi dau lên DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { var dm = (from d in help.ent.Phieu_Nhap_Kho join l in help.ent.Loai_Phieu_Nhap on d.ID_Loai_Phieu_Nhap equals l.ID_Loai_Phieu_Nhap join ct in help.ent.Chi_Tiet_Phieu_Nhap_Vat_Tu on d.Ma_phieu_nhap equals ct.Ma_phieu_nhap join k in help.ent.DM_Kho on d.ID_kho equals k.ID_kho join v in help.ent.DM_Vat_Tu on ct.Ma_vat_tu equals v.Ma_vat_tu where d.Da_phan_kho == true && (d.isGoiDau == true || l.Ma_loai_phieu_nhap.Contains("T")) && ct.Ma_vat_tu .Contains(mavt) select new { d.Ma_phieu_nhap, ct.Ma_vat_tu , d.Ngay_lap, so_luong= ct.So_luong_thuc_lanh, d.ID_kho, k.Ten_kho, d.ID_Loai_Phieu_Nhap, l.Ma_loai_phieu_nhap , }).ToList(); dbcxtransaction.Commit(); DataTable ds = Utilities.clsThamSoUtilities.ToDataTable(dm); return ds; } }
public void SignIn(object passwordBox) { Validation = "Connecting..."; var password = Encrypter.HashPassword(((PasswordBox)passwordBox).Password); using (var connector = new DatabaseHelper()) { var result = connector.Get(Login, password); if (result!=null) { if (result.IsAdmin) { var entryPage = new AdminPage(); entryPage.Show(); CloseAction(); } else { var entryPage = new EntryPage(Login); entryPage.Show(); CloseAction(); } } else { Validation = "Username or password is incorrect!"; } } }
public bool CheckTonTaiSoDK() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); bool has = help.ent.Dm_Kho_Muon_Ngoai.Any(cus => cus.Ten_kho_muon == Ten_kho); return has; }
/// <summary> /// [Bug] Xóa Item có Liên Kết khóa ngoại với bảng Vật Tư /// </summary> /// <returns>bool</returns> public int Delete(DM_Don_vi_tinh dvt) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); help.ent.DM_Don_vi_tinh.Attach(dvt); help.ent.DM_Don_vi_tinh.Remove(dvt); return help.ent.SaveChanges(); //Mở //m_dbConnection.Open(); ////Chuẩn bị //string sql = ""; //sql += "Delete from DM_Don_vi_tinh "; //sql += "WHERE ID_Don_vi_tinh=@ID_Don_vi_tinh"; //SqlCommand command = new SqlCommand(sql, m_dbConnection); //command.Parameters.Add("@ID_Don_vi_tinh", SqlDbType.Int).Value = ID_Don_vi_tinh; //command.CommandType = CommandType.Text; ////Run //int result = command.ExecuteNonQuery(); ////Đóng //m_dbConnection.Close(); //return result; }
// public UserGunSetupViewModel UserSetup { get; set; } /// <summary> /// ViewModel right before one enters a session. Set setupId to 0 for new setup. /// </summary> /// <param name="helper"></param> /// <param name="setupId"></param> public SetupSessionViewModel(DatabaseHelper helper, int setupId) { dbHelper = helper; // UserSetup = new UserGunSetupViewModel(setupId, helper); }
private void btnFinish_Click(object sender, RoutedEventArgs e) { if (GlobalMethods.IsLastBatch()) { try { log.Info("write result to database."); btnFinish.IsEnabled = false; SetInfo("正在关闭,请稍等!",Brushes.DarkGreen); this.Refresh(); database = new DatabaseHelper(); string sErrMsg = ""; bool bSaveOk = database.Save(ref sErrMsg); if (!bSaveOk) { SetInfo("写入数据库失败,错误原因为: " + sErrMsg, Brushes.Red); return; } } catch (Exception ex) { SetInfo("写入数据库失败" + string.Format("原因:{0}", ex.Message), Brushes.Red); return; } try { //save measure data System.IO.StringWriter strWriter = new System.IO.StringWriter(); XmlTextWriter xmltw = new XmlTextWriter(strWriter); DataSet ds = new DataSet(); ds.Tables.Add(tbl); XmlDocument xmlDoc = new XmlDocument(); ds.WriteXml(xmltw, XmlWriteMode.IgnoreSchema); string strXml = strWriter.ToString(); string sFile = Helper.GetSaveFolder() + "report.xml"; using (StreamWriter sw = new StreamWriter(sFile)) { sw.Write(strXml); } string thisRunFile = Helper.GetSaveFolder() + Helper.GetDate() + GlobalVals.startTimeHHMMSS + "report.xml"; File.Copy(sFile, thisRunFile); string sExeParentFolder = Helper.GetExeParentFolder(); File.Copy(sFile, sExeParentFolder + "Data\\lastReport.xml", true); ModifySeqNo(); } catch (Exception ex) { log.Error(ex.Message); SetInfo(ex.Message, Brushes.Red); return; } } if (onFinished != null) onFinished(); }
/// <summary> /// Initializes this instance with defaults. /// </summary> /// <remarks></remarks> public void Initialize() { UseMySQL = true; DatabaseName = "MCForge"; MySQLHost = "127.0.0.1"; MySQLPort = 3306; MySQLUser = "******"; MySQLPassword = "******"; Database = DatabaseHelper.Create(); }
public override int BoDuyet(int id) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { PhieuNhap pn = new PhieuNhap(); if (pn.BoDuyet(id,help) == 1) { { var pnk = (from d in help.ent.Phieu_Nhap_Kho where d.ID_phieu_nhap == id select d).FirstOrDefault(); if (pnk == null) return 0; var entryPointCTPN = (from d in help.ent.Chi_Tiet_Phieu_Nhap_Vat_Tu where d.Ma_phieu_nhap == pnk.Ma_phieu_nhap select d).ToList(); if (entryPointCTPN.Count == 0) return 0; for (int i = 0; i < entryPointCTPN.Count; i++) { string mavattu = entryPointCTPN[i].Ma_vat_tu; int idcl = (int)entryPointCTPN[i].Id_chat_luong; string maphieu = entryPointCTPN[i].Ma_phieu_nhap; decimal sl = (decimal)entryPointCTPN[i].So_luong_thuc_lanh; DateTime ngay_xuat = (DateTime)pnk.Ngay_lap; string dien_giai = pnk.Ly_do; var entryPointGD = (from d in help.ent.Vat_Tu_Goi_Dau_Ky where d.ID_kho == pnk.ID_kho && d.Ma_vat_tu == mavattu && d.ID_chat_luong == idcl select d).FirstOrDefault(); if (entryPointGD == null || entryPointGD.So_Luong < sl) { return 0; } entryPointGD.So_Luong = entryPointGD.So_Luong - sl; help.ent.Vat_Tu_Goi_Dau_Ky.Attach(entryPointGD); help.ent.Entry(entryPointGD).State = EntityState.Modified; help.ent.SaveChanges(); } dbcxtransaction.Commit(); return 1; } } } return base.BoDuyet(id); }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync( Microsoft.ApplicationInsights.WindowsCollectors.Metadata | Microsoft.ApplicationInsights.WindowsCollectors.Session); this.InitializeComponent(); this.Suspending += OnSuspending; SQLITE_PLATFORM = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(); DBHelper = new DatabaseHelper(SQLITE_PLATFORM,DB_PATH); }
public static Chi_Tiet_Phieu_Nhap_Vat_Tu getChitiet(int id ) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { var dm = (from d in help.ent.Chi_Tiet_Phieu_Nhap_Vat_Tu where d.ID_chi_tiet_phieu_nhap_vat_tu == id select d).FirstOrDefault(); return dm; } }
//public static object getAll() //{ // DatabaseHelper help = new DatabaseHelper(); // help.ConnectDatabase(); // using (var dbcxtransaction = help.ent.Database.BeginTransaction()) // { // var dm = from d in help.ent.Chi_Tiet_Ton_Kho // select new // { // d.ID_Chi_tiet_ton_kho, // d.ID_Ton_kho, // d.Ma_phieu, // d.So_luong, // d.Tang_Giam // }; // dbcxtransaction.Commit(); // return (object)dm.ToList(); // } //} //public bool CheckTonTaiSoDK(int idkho, string maVT) //{ //// DatabaseHelper help = new DatabaseHelper(); //// help.ConnectDatabase(); //// var temp = help.ent.Ton_kho.Where( ////i => i.Ma_vat_tu == maVT ////).ToList(); //// string name = ""; //// temp.ToList().ForEach((n) => //// { //// name = n.Ten_vat_tu; //// }); //// return name; //} public int Insert() { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); // insert using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { try { //var t = new Chi_Tiet_Ton_Kho //Make sure you have a table called test in DB //{ // ID_Ton_kho = this.ID_Ton_kho, // Ma_phieu = this.Ma_phieu, // ID = Guid.NewGuid(), // So_luong = this.So_luong, // Ngay_thay_doi = this.Ngay_thay_doi, // Tang_Giam = this.Tang_giam, //}; //help.ent.Chi_Tiet_Ton_Kho.Add(t); //help.ent.SaveChanges(); //dbcxtransaction.Commit(); return 1; } catch (Exception ex) { dbcxtransaction.Rollback(); return 0; } } //DatabaseHelper help = new DatabaseHelper(); //help.ConnectDatabase(); //// insert //try //{ // var t = new DM_Kho //Make sure you have a table called test in DB // { // ID_kho = this.ID_kho, // Ten_kho = this.Ten_kho, // ID = Guid.NewGuid(), // }; // help.ent.DM_Kho.Add(t); // help.ent.SaveChanges(); // return 1; //} //catch (Exception ex) //{ // return 0; //} }
/// <summary> /// ham kiem tra co vat tu nao da duyet trong phieu nhap chua /// </summary> /// <param name="ma_Phieunhap"></param> /// <returns>false : chua co , true: da co </returns> public static bool KTVTChuaDuyet(string ma_Phieunhap) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); var entryPoint = (from ep in help.ent.Chi_Tiet_Phieu_Nhap_Vat_Tu where ep.Ma_phieu_nhap.Equals(ma_Phieunhap) && ep.Da_duyet == true select ep).ToList(); if (entryPoint.Count == 0) return false;// chua co phan tu nao da duyet trong danh sach return true; }
public int Delete(Loai_Phieu_Nhap dm) { DatabaseHelper help = new DatabaseHelper(); help.ConnectDatabase(); using (var dbcxtransaction = help.ent.Database.BeginTransaction()) { help.ent.Loai_Phieu_Nhap.Attach(dm); help.ent.Loai_Phieu_Nhap.Remove(dm); int temp = help.ent.SaveChanges(); dbcxtransaction.Commit(); return temp; } }
public PedidoRepository() { _databaseHelper = new DatabaseHelper(); }
public async Task UpdateProductForSupplier() { await using var context = DatabaseHelper.CreateInMemoryDatabaseContext(nameof(UpdateProductForSupplier)); var supplierRes = await context.AddAsync(ValidModelCreator.Supplier()); var supplierId = supplierRes.Entity.Id; var productRes = await context.AddAsync(ValidModelCreator.Product(supplierId)); var productId = productRes.Entity.Id; //test update var updateProductCmd1 = new UpdateProductForSupplierCommand { SupplierId = supplierId, ProductId = productId, Label = "Something new", Price = 55.5m, }; var updateProductForSupplierCommandHandler = new UpdateProductForSupplierCommandHandler(context); var response1 = await updateProductForSupplierCommandHandler.Handle(updateProductCmd1, CancellationToken.None); Assert.True(response1.Success); var getUpdatedProductQuery1 = new GetProductForSupplierByIdQuery { SupplierId = supplierId, ProductId = productId, }; var queryOneHandler = new GetProductForSupplierByIdQueryHandler(context); var queryResp1 = await queryOneHandler.Handle(getUpdatedProductQuery1, CancellationToken.None); Assert.True(queryResp1.Success); Assert.Equal(supplierId, queryResp1.Data.SupplierId); Assert.Equal(productId, queryResp1.Data.Id); Assert.Equal("Something new", queryResp1.Data.Label); Assert.Equal(55.5m, queryResp1.Data.Price); // test another update var updateProductCmd2 = new UpdateProductForSupplierCommand { SupplierId = supplierId, ProductId = productId, Label = "another thing", Price = 66.45798m, }; var response2 = await updateProductForSupplierCommandHandler.Handle(updateProductCmd2, CancellationToken.None); Assert.True(response2.Success); var queryResp2 = await queryOneHandler.Handle( new GetProductForSupplierByIdQuery { SupplierId = supplierId, ProductId = productId }, CancellationToken.None); Assert.Equal(supplierId, queryResp2.Data.SupplierId); Assert.Equal(productId, queryResp2.Data.Id); Assert.Equal("another thing", queryResp2.Data.Label); Assert.Equal(66.45798m, queryResp2.Data.Price); // test no update if invalid data provided var reqInvalidSupplier = new UpdateProductForSupplierCommand { SupplierId = supplierId + 1, ProductId = productId, Price = 50.0m, Label = "should not be changed", }; var response3 = await updateProductForSupplierCommandHandler.Handle(reqInvalidSupplier, CancellationToken.None); Assert.False(response3.Success); var queryResponse3 = await queryOneHandler.Handle( new GetProductForSupplierByIdQuery { SupplierId = supplierId, ProductId = productId, }, CancellationToken.None); Assert.True(queryResponse3.Success); Assert.Equal(supplierId, queryResponse3.Data.SupplierId); Assert.Equal(productId, queryResponse3.Data.Id); Assert.Equal("another thing", queryResponse3.Data.Label); Assert.Equal(66.45798m, queryResponse3.Data.Price); }