sql Transaktion 2 insert Statements
HejJeg har en metode der køre 2 insert statements, men den køre det ene statement 2 gange ser det ud til i min Database - får jeg 2 af dem samme record hvergang jeg køre det??
Kode
public Sample insertSampleWithproject(string sample_Strain, string sample_EksternalNo, DateTime sample_Date, string materiale, string diagnose,
int patient_ID, int placement_ID, int location_ID, int sampleType_ID, int Project_ID)
{
var newSample = new Sample();
var newPatient = new Patient();
var newPlacement = new Placement();
var newLocation = new Location();
var newSampleType = new SampleType();
var newProject = new Project();
newSample.Patient = newPatient;
newSample.Placement = newPlacement;
newSample.Location = newLocation;
newSample.SampleType = newSampleType;
newSample.Project = newProject;
try
{
using(conn)
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
try
{
using (var cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = "INSERT INTO HFL_Sample(Sample_Strain,Sample_EksternalNo,Sample_Date,Materiale,Diagnose, Patient_ID, Placement_ID ,Location_ID ,SampleType_ID)" +
"VALUES (@Sample_Strain,@Sample_EksternalNo,@Sample_Date,@Materiale,@Diagnose, @Patient_ID, @Placement_ID ,@Location_ID ,@SampleType_ID); SELECT SCOPE_IDENTITY() AS [lastInsertedSampleID]";
cmd.Parameters.AddWithValue("@Sample_Strain", sample_Strain);
cmd.Parameters.AddWithValue("@Sample_EksternalNo", sample_EksternalNo);
cmd.Parameters.AddWithValue("@Sample_Date", sample_Date);
cmd.Parameters.AddWithValue("@Materiale",materiale);
cmd.Parameters.AddWithValue("@Diagnose",diagnose);
cmd.Parameters.AddWithValue("@Patient_ID",patient_ID);
cmd.Parameters.AddWithValue("@Placement_ID",placement_ID);
cmd.Parameters.AddWithValue("@Location_ID", location_ID);
cmd.Parameters.AddWithValue("@SampleType_ID", sampleType_ID);
Console.WriteLine("First CommandText" + cmd.CommandText);
cmd.ExecuteNonQuery();
newSample.Patient.Patient_ID = patient_ID;
newSample.Placement.Placement_ID = placement_ID;
newSample.Location.Location_ID = location_ID;
newSample.SampleType.SampleType_ID = sampleType_ID;
int lastInsertedSampleID = Convert.ToInt32(cmd.ExecuteScalar());
cmd.CommandText = "INSERT INTO HFL_ProjSample (Sample_ID, Project_ID) VALUES (@Sample_ID, @Project_ID)";
cmd.Parameters.AddWithValue("@Sample_ID", lastInsertedSampleID);
cmd.Parameters.AddWithValue("@Project_ID", Project_ID);
Console.WriteLine("First CommandText" + cmd.CommandText);
cmd.ExecuteNonQuery();
newSample.Project.Project_ID = Project_ID;
}
trans.Commit();
}
catch (Exception excep)
{
trans.Rollback();
Console.WriteLine("DBSample : insertSampleWithproject" + excep);
Console.WriteLine("Get exception Type : " + excep.GetType());
Console.WriteLine("Exception Message : " + excep.Message);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return newSample;
}
please help tak :)