我这里有Linq-to-SQL代码,它在各自的表中将数据提交到数据库中,
PatientInformation
和ResponsibleParty
:
public void addPatientInformation() {
using(DbClassesDataContext myDb = new DbClassesDataContext(dbPath)){
PatientInfo patientInfo = new PatientInfo();
patientInfo.Phy_ID = physcianID;
patientInfo.Pat_First_Name = txtFirstName.Text;
patientInfo.Pat_Middle_Name = txtMiddleName.Text;
patientInfo.Pat_Last_Name = txtLastName.Text;
patientInfo.Pat_Gender = cmbGender.Text;
patientInfo.Pat_Marital_Status = cmbMaritalStatus.Text;
patientInfo.Pat_Date_Of_Birth = dtpDOB.Value;
patientInfo.Pat_Home_Add = txtHomeAdd.Text;
patientInfo.Pat_Home_Num = txtPhone.Text;
patientInfo.Pat_Work_Add = txtWorkAdd.Text;
patientInfo.Pat_Work_Num = txtWorkPhone.Text;
patientInfo.Pat_Prim_Physician = txtPrimPhysician.Text;
patientInfo.Pat_Ref_Physician = txtRefePhysician.Text;
myDb.PatientInfos.InsertOnSubmit(patientInfo);
myDb.SubmitChanges();
}
}
public void addResponsiblePartyInformation() {
using(DbClassesDataContext myDb = new DbClassesDataContext(dbPath)){
ResponsibleParty responsibleParty = new ResponsibleParty();
responsibleParty.Res_First_Name = txtResFirstName.Text;
responsibleParty.Res_Middle_Init = txtResMiddleName.Text;
responsibleParty.Res_Last_Name = txtResLName.Text;
responsibleParty.Res_Gender = cmbResGender.Text;
responsibleParty.Res_Marital_Status = cmbResMaritalStatus.Text;
responsibleParty.Res_Date_Of_Birth = dtpResDOB.Value;
responsibleParty.Res_Home_Add = txtResHomeAdd.Text;
responsibleParty.Res_Home_Num = txtResPhone.Text;
responsibleParty.Res_Work_Add = txtResWorkAdd.Text;
responsibleParty.Res_Work_Num = txtResWorkPhone.Text;
myDb.ResponsibleParties.InsertOnSubmit(responsibleParty);
myDb.SubmitChanges();
}
一个名为
的方法public void submitInformationToDatabase() {
addPatientInformation();
addResponsiblePartyInformation();
MessageBox.Show("Patient Demographics Has Been added.");
}
有没有办法可以立刻提交?
答案 0 :(得分:6)
两个选项:
SubmitChanges()
(也许可以选择)对于第二种情况,可以使用TransactionScope
来执行此操作,而无需更改这两种方法:
using(var tran = new TransactionScope()) {
method1(...);
method2(...);
tran.Complete();
}
或使用其他方法(添加可选参数后):
using(var ctx = new SomeDataContext(...)) {
method1(ctx, ..., submitChanges: false);
method2(ctx, ..., submitChanges: false);
ctx.SubmitChanges();
}
答案 1 :(得分:2)
如果您可以将代码重构为类似下面示例的内容,则两个记录都将插入到同一submit
中。
using(DbClassesDataContext myDb = new DbClassesDataContext(dbPath)){
myDb.PatientInfos.InsertOnSubmit(patientInfo);
myDb.ResponsibleParties.InsertOnSubmit(responsibleParty);
myDb.SubmitChanges();
}
答案 2 :(得分:2)
使用两种方法将连接作为参数传递,并使用System.Transaction:
public void submitInformationToDatabase() {
using (System.Transactions.TransactionScope tr = new System.Transactions.TransactionScope())
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(dbPath);
con.Open();
addPatientInformation(con);
addResponsiblePartyInformation(con);
tr.Complete();
}
MessageBox.Show("Patient Demographics Has Been added.");
}