Takes long time to insert rows in SQL Server 2008 R2 - c#

I have over 200,000 records in c# Winforms gridview, it takes around an hour to get inserted into my database. I'm trying to improve the performance of this insert. I'm looking to insert all of the records within 5 to 10 minutes.
I am using For loop to populate each and every row to get insert into DB with a SQL transactions and I don't think that SqlBulkCopy will work out because all 200,000 records needs to be validated with the DB before insertion into DB.
Save-Function:
if (chkretailprice.Checked)
{
DataTable dt_grid = (DataTable)gcPromotion.DataSource;
dt_grid.AcceptChanges();
for (int tt = 0; tt < gvPromotion.RowCount; tt++)
{
gvPromotion.FocusedRowHandle = tt;
double dRGridMinus = Convert.ToDouble(gvPromotion.GetRowCellValue(tt, gvPromotion.Columns["PromotionalRetailPrice"]));
string sItem = Convert.ToString(gvPromotion.GetRowCellValue(tt, gvPromotion.Columns["ItemName"]).ToString());
string sPack = Convert.ToString(gvPromotion.GetRowCellValue(tt, gvPromotion.Columns["Package"]).ToString());
if (dRGridMinus < 0)
{
gvPromotion.FocusedRowHandle = tt;
MessageBoxInfo("Promotional RetailPrice contains Negative Values for this ItemName-'" + sItem + "' & Package-'" + sPack + "'");
gvPromotion.Focus();
return;
}
}
int iReCount = dt_grid.Select("PromotionalRetailPrice='0.00'").Length;
if (iReCount != 0)
{
MessageBoxInfo("Promotional RetailPrice Must not be 0");
gvPromotion.Focus();
return;
}
}
if (rgPromotion.Checked)
{
for (int p = 0; p < gvPromotion.RowCount; p++)
{
string[] sbranchArr = sBranchIDs.Split(',');
for (int pp = 0; pp < sbranchArr.Length; pp++)
{
objProEntity.PromotionMasterId = objProEntity.PromotionMasterId;
objProEntity.BranchId = Convert.ToInt32(sbranchArr[pp]);//gvPromotion.GetRowCellValue(p, gvPromotion.Columns["BranchID"]));
objProEntity.ItemId = Convert.ToInt64(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ItemID"]));
objProEntity.PackId = Convert.ToInt32(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PackTypeID"]));
objProEntity.PromotionValueType = Convert.ToString(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionValueType"]));
objProEntity.PromotionValue = Convert.ToString(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionValue"]));
if (chkretailprice.Checked && chkwholesaleprice.Checked)// when both retailprice & wholesaleprice checkbox is checked
{
objProEntity.ActualRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualRetailPrice"]));
objProEntity.PromoRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalRetailPrice"]));
objProEntity.ActualWholeSalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualWholeSalePrice"]));
objProEntity.PromoWholesalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalWholeSalePrice"]));
}
else if (chkretailprice.Checked)// when retailprice checkbox is checked
{
objProEntity.ActualRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualRetailPrice"]));
objProEntity.PromoRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalRetailPrice"]));
objProEntity.ActualWholeSalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualWholeSalePrice"]));
objProEntity.PromoWholesalePrice = Convert.ToDecimal(0);
}
else if (chkwholesaleprice.Checked)// when wholesaleprice checkbox is checked
{
objProEntity.ActualRetailPrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualRetailPrice"]));
objProEntity.PromoRetailPrice = Convert.ToDecimal(0);
objProEntity.ActualWholeSalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["ActualWholeSalePrice"]));
objProEntity.PromoWholesalePrice = Convert.ToDecimal(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionalWholeSalePrice"]));
}
objProEntity.DiscountAllowed = Convert.ToBoolean(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["DiscountAllowed"]));
DataTable dt_Check = new DataTable();
dt_Check = SalesPromotionData.IsCheckItemExists(objProEntity, SQLTrans);
if (dt_Check.Rows.Count == 0)
{
if (!IsEdit)
{
DataTable dt_child = SalesPromotionData.InsertChildData(objProEntity, SQLTrans); // Insert Child Details when isEdit=false
}
else
{
if (gvPromotion.Columns.Contains(gvPromotion.Columns["PromotionChildId"]))
if ((DBNull.Value.Equals(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]))) || (gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]) == "") || Convert.ToString(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]).ToString()) == "0")
{
objProEntity.PromotionMasterId = masterid;
SalesPromotionData.InsertChildData(objProEntity, SQLTrans);// insert child details when isEdit=true
}
else
{
objProEntity.PromotionChildId = Convert.ToInt64(gvPromotion.GetRowCellValue(p, gvPromotion.Columns["PromotionChildId"]).ToString());
SalesPromotionData.UpdateChildDetails(objProEntity, SQLTrans); // update child details when isEdit=true
}
else
{
objProEntity.PromotionMasterId = masterid;
SalesPromotionData.InsertChildData(objProEntity, SQLTrans);// insert child details when isEdit=true
}
}
}
}
}
}

Normally, you'd stage your data into the database by bulk inserting it into [a] work table(s), with no referential integrity or anything -- just the raw data plus any [non-unique] indices you might need. Once you've got it staged, you can then:
Validate the data in the work table(s) against your database and
apply it to the "real" tables in question.

Related

datagridview dont let me change the values of the celll

I'm new in c# , but i can do the basics. i need to change all the values of a column and then update the datagrid. The values are in 20170202 format and i want them like 2017-02-02. the method i did works fine but when i try to set the value to the column it wont change.
here is the code:
private void fixAlldates(DataGridView dataGridView2)
{
string aux1 = "";
for (int x = 0; x < dataGridView2.Rows.Count; x++)
{
if (dataGridView2.Rows[x].Cells[4].Value.ToString() != null)
{
aux1 = dataGridView2.Rows[x].Cells[4].Value.ToString();
dataGridView2.Rows[x].Cells[4].Value = fixDate(aux1);
}
if (dataGridView2.Rows[x].Cells[5].Value.ToString() != null)
{
dataGridView2.Rows[x].Cells[5].Value = fixDate(dataGridView2.Rows[x].Cells[5].Value.ToString());
}
dataGridView2.Refresh();
MessageBox.Show(fixDate(aux1); ----> shows result like i want ex: 2017-02-02
MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); ----> shows 2070202
}
}
private string fixDate(string p)
{
if (p == null) return "No especificado";
String fecha = "" + p.Substring(0, 4) + "-" + p.Substring(4, 2) + "-" + p.Substring(6, 2) + "";
return fecha;
}
sorry for my bad english , im a little bit rusty
Edit:
I fill the data with bindingSource.
private void LlenarProductos(string rut)
{
this.rut = rut;
POLbindingSource1.DataSource = null;
dataGridView2.DataSource = null;
DataClasses1DataContext dc = new DataClasses1DataContext();
dc.CommandTimeout = 0;
System.Data.Linq.Table<ASE_PRODUCTOASEGURADO> producto = dc.GetTable<ASE_PRODUCTOASEGURADO>();
var todoprod = from p in producto
where p.RUT == int.Parse(rut)
select new
{
p.POLIZA,
p.SOCIO,
p.SUCURSAL,
p.COD_PROPUESTA,
p.FECHA_ALTA_COTI,
p.FECHA_ALTA_VCTO,
p.NOMBRE_PRODUCTO
};
POLbindingSource1.DataSource = todoprod; // binding source
dataGridView2.DataSource = POLbindingSource1; // filll
this.dataGridView2.Columns["POLIZA"].HeaderText = "Poliza";
this.dataGridView2.Columns["Socio"].HeaderText = "Socio";
this.dataGridView2.Columns["Sucursal"].HeaderText = "Sucursal";
this.dataGridView2.Columns["COD_PROPUESTA"].HeaderText = "Propuesta";
this.dataGridView2.Columns["FECHA_ALTA_COTI"].HeaderText = "Fecha Cotizacion";
this.dataGridView2.Columns["FECHA_ALTA_VCTO"].HeaderText = "Fecha Vencimiento";
this.dataGridView2.Columns["NOMBRE_PRODUCTO"].HeaderText = "Producto";
// fixAlldates(dataGridView2);
}
From msdn https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.value(v=vs.110).aspx.
The Value property is the actual data object contained by the cell.
So basically the line MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); is getting the value of the underlying data, whereas MessageBox.Show(fixDate(aux1); is actually formatting the date as you require.
You're overlooking the fact that although you're seeing the data in the grid in a specific way, you're not actually changing the data itself.
UPDATE
To actually edit the data in a cell see here

Insert multiple records in database using parallel.foreach

I am trying to insert around 5000 records in database using foreach loop. It is taking around 10 min which is not acceptable as per the requirement. I also thought about the approach in which first insert the records in a datatable and then converting it into XML pass it to stored procedure which do the insertion. But unfortunately it is not getting fit in my situation. Now i am doing the same thing using parallel.foreach but after inserting 10 records i am getting "Unique constraint violation for the primary key" error msg. As i am new to parallel programming so not getting the solution for it. Below is my code that i have done so for.
public ActionResult ChannelBulkUpload(HttpPostedFileBase excelFile)
{
bool flag = true;
string path = Server.MapPath("~/Content/UploadFolder/" + excelFile.FileName);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
excelFile.SaveAs(path);
DataTable dt = GetDataTableFromExcel(excelFile, true);
ParallelOptions options = new ParallelOptions
{
MaxDegreeOfParallelism = 4
};
Parallel.ForEach(dt.AsEnumerable(), row =>
{
flag = true;
decimal Key = 0;
string value = "";
decimal channelMstKey = 0;
decimal channelGrpMstKey = 0;
decimal srcFuncKey = 0;
string ExcelMasterChDisplayName = row["MASTER_CHANNEL_DISPLAY_NAME"].ToString();
string ExcelGenreValue = row["GENRE"].ToString();
string ExcelAdsharpValue = row["ADSHARP"].ToString();
string ExcelClusterValue = row["CLUSTER"].ToString();
string ExcelNetworkValue = row["NETWORK"].ToString();
string ExcelBroadCastValue = row["BROADCAST"].ToString();
string ExcelFunctionalAreaname = row["FUNCTIONAL_AREA"].ToString();
string[] Ch_Grp_types = { "GENRE", "ADSHARP", "CLUSTER", "NETWORK", "PLATFORM" };
BarcDataContext bc = new BarcDataContext();
srcFuncKey = bc.REF_SRC_FUNC_AREA.Where(m => m.SRC_FUNC_AREA == ExcelFunctionalAreaname).FirstOrDefault().SRC_FUNC_KEY;
for (int j = 0; j < Ch_Grp_types.Length && flag; j++)
{
if (Ch_Grp_types[j] == "GENRE")
{
Key = 1;
value = ExcelGenreValue;
}
else if (Ch_Grp_types[j] == "NETWORK")
{
Key = 2;
value = ExcelNetworkValue;
}
else if (Ch_Grp_types[j] == "ADSHARP")
{
Key = 3;
value = ExcelAdsharpValue;
}
else if (Ch_Grp_types[j] == "CLUSTER")
{
Key = 4;
value = ExcelClusterValue;
}
else if (Ch_Grp_types[j] == "PLATFORM")
{
Key = 5;
value = ExcelBroadCastValue;
}
DIM_CHANNEL_MST objChMst = bc.DIM_CHANNEL_MST.Where(m => m.CHANNEL_MST_NAME_UPPER == ExcelMasterChDisplayName.ToUpper().Trim()).FirstOrDefault();
if (objChMst == null)
{
flag = false;
}
else
{
if (!string.IsNullOrEmpty(value))
{
var query =
(from A in bc.XREF_CH_GRP_DET_TAG
join B in bc.XREF_CH_GRP_MST_TAG on A.CH_GRP_MST_KEY equals B.CH_GRP_MST_KEY
where A.IS_ACTIVE == "Y" && B.IS_ACTIVE == "Y" && B.CH_GRP_TYPE_KEY == Key && B.CH_GRP_MST_NAME_UPPER == value.ToUpper()
select new XrefChannelGrpDetailTagVM
{
channelGrpDetKey = A.CH_GRP_DET_KEY,
channelGrpMasterNameUpper = B.CH_GRP_MST_NAME_UPPER,
}).Distinct().ToList();
var query2 =
(from A in bc.XREF_CH_GRP_DET_TAG
join B in bc.XREF_CH_GRP_MST_TAG on A.CH_GRP_MST_KEY equals B.CH_GRP_MST_KEY
where A.CHANNEL_MST_KEY == objChMst.CHANNEL_MST_KEY && B.CH_GRP_TYPE_KEY == Key && B.SRC_FUNC_KEY == srcFuncKey
select new XrefChannelGrpDetailTagVM
{
sr_no = A.SR_NO,
channelMstKey = A.CHANNEL_MST_KEY,
channelGrpDetKey = A.CH_GRP_DET_KEY,
channelGrpMstKey = A.CH_GRP_MST_KEY,
srcFuncKey = B.SRC_FUNC_KEY,
channelGrpTypeKey = B.CH_GRP_TYPE_KEY
}).Distinct().ToList();
XREF_CH_GRP_MST_TAG objXrefChGrpMst = bc.XREF_CH_GRP_MST_TAG.Where(m => m.CH_GRP_TYPE_KEY == Key && m.SRC_FUNC_KEY == srcFuncKey && m.CH_GRP_MST_NAME_UPPER == value.ToUpper()).FirstOrDefault();
if (objXrefChGrpMst != null)
{
channelMstKey = objChMst.CHANNEL_MST_KEY;
channelGrpMstKey = objXrefChGrpMst.CH_GRP_MST_KEY;
XREF_CH_GRP_DET_TAG objGrpDetail = new XREF_CH_GRP_DET_TAG();
if (query.Count == 0)
{
objGrpDetail.CH_GRP_DET_KEY = Get_Max_Of_Ch_Grp_Det_Key();
}
else
{
foreach (var detKey in query)
{
if (detKey.channelGrpMasterNameUpper == value.ToUpper())
{
objGrpDetail.CH_GRP_DET_KEY = detKey.channelGrpDetKey;
}
else
{
objGrpDetail.CH_GRP_DET_KEY = Get_Max_Of_Ch_Grp_Det_Key();
}
}
}
if (query2.Count > 0)
{
foreach (var abc in query2)
{
if (abc.channelMstKey == objChMst.CHANNEL_MST_KEY && abc.srcFuncKey == srcFuncKey && abc.channelGrpTypeKey == Key)
{
if (abc.channelGrpDetKey == objGrpDetail.CH_GRP_DET_KEY && abc.channelGrpMstKey == objXrefChGrpMst.CH_GRP_MST_KEY)
{
//Reject
}
else
{
//Update
XREF_CH_GRP_DET_TAG obj = bc.XREF_CH_GRP_DET_TAG.Where(m => m.SR_NO == abc.sr_no).FirstOrDefault();
obj.CH_GRP_DET_KEY = objGrpDetail.CH_GRP_DET_KEY;
obj.CH_GRP_MST_KEY = objXrefChGrpMst.CH_GRP_MST_KEY;
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.SaveChanges();
}
}
else
{
//Insert
objGrpDetail.CH_GRP_MST_KEY = channelGrpMstKey;
objGrpDetail.CHANNEL_MST_KEY = channelMstKey;
objGrpDetail.SR_NO = Get_Max_Of_XREF_CH_GRP_DET();
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.XREF_CH_GRP_DET_TAG.Add(objGrpDetail);
bc.SaveChanges();
}
}
}
else
{
objGrpDetail.CH_GRP_MST_KEY = channelGrpMstKey;
objGrpDetail.CHANNEL_MST_KEY = channelMstKey;
objGrpDetail.SR_NO = Get_Max_Of_XREF_CH_GRP_DET();
objGrpDetail.CH_GRP_DET_KEY = objGrpDetail.CH_GRP_DET_KEY;
objGrpDetail.CREATE_DATE = DateTime.Now;
objGrpDetail.LAST_UPD_DATE = DateTime.Now;
objGrpDetail.IS_ACTIVE = "Y";
bc.XREF_CH_GRP_DET_TAG.Add(objGrpDetail);
bc.SaveChanges();
}
}
}
}
}
});
TempData["SuccessMsg"] = "Records uploaded Successfully";
return RedirectToAction("CreateChannel");
}
Getting error when generating the primary key value using the below function :
public static decimal Get_Max_Of_XREF_CH_GRP_DET()
{
try
{
BarcDataContext bc = new BarcDataContext();
return bc.XREF_CH_GRP_DET_TAG.Max(m => m.SR_NO) + 1;
}
catch (Exception e)
{
return 1;
}
}
Where SR_NO is the primary key in that table.
Any help will be very much appreciated. Thanks in advance.
The fastest way to do such inserts is using ADO.NET, specifically, SQL Bulk Insert. If you're using SQL Server as your database, the relevant code will be something like this:
DataTable dt = GetDataTableFromExcel(excelFile, true);
using (var copy = new SqlBulkCopy(yourConnectionString) //There are other overloads too
{
BulkCopyTimeout = 10000,
DestinationTableName = dt.TableName,
})
{
foreach (DataColumn column in dt.Columns)
{
copy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
}
copy.WriteToServer(dt);
}
Please look at my comment to other question
You could use guid as primary key into your table. It would help you to avoid problem with ##IDENTITY. At first you should generate new guid-identity, thank insert the generated value into a row

How to load column data from DataReader?

I'm porting application to ASP.Net 5.0 with EF7 and found several problems. One of the issues is MS have dropped DataTable. I'm trying to transfer a bit of code to not use DataTable but read from SQLDataReader and record this into entities I have. I have to read data by columns, but looks like datareader can read only once.
The old code:
Series[] arrSeries = new Series[dt.Columns.Count - 1];
IList<Categories> arrCats = new List<Categories>();
Categories arrCat = new Categories();
foreach (DataColumn dc in dt.Columns)
{
var strarr = dt.Rows.Cast<DataRow>().Select(row => row[dc.Ordinal]).ToList();
if (dc.Ordinal == 0)
{
arrCat.category = strarr.Select(o => new Category { label = o.ToString() }).ToList();
}
else
{
Series s = new Series()
{
seriesname = dc.ColumnName,
renderas = null,
showvalues = false,
data = strarr.Select(o => new SeriesValue { value = o.ToString() }).ToList()
};
arrSeries[dc.Ordinal - 1] = s;
}
}
arrCats.Add(arrCat);
MultiFusionChart fusChart = new MultiFusionChart
{
chart = dictAtts,
categories = arrCats,
dataset = arrSeries
};
return fusChart;
The new code:
Series[] arrSeries = new Series[colColl.Count - 1];
IList<Categories> arrCats = new List<Categories>();
Categories arrCat = new Categories();
arrCat.category = new List<Category>();
for (int i = 0; i < reader.FieldCount; i++)
{
Series s = new Series()
{
seriesname = reader.GetName(i),
renderas = null,
showvalues = false
};
while (reader.Read())
{
if (i == 0)
{
Category cat = new Category();
cat.label = reader.GetValue(i).ToString();
arrCat.category.Add(cat);
}
else
{
SeriesValue sv = new SeriesValue();
sv.value = reader.GetValue(i).ToString();
s.data.Add(sv);
arrSeries[i - 1] = s;
}
}
}
arrCats.Add(arrCat);
MultiFusionChart fusChart = new MultiFusionChart
{
chart = dictAtts,
categories = arrCats,
dataset = arrSeries
};
return fusChart;
Where the code works, it returns null for Series. And I believe this is because reader went to the end while recording Categories. As far as I know it is not possible to reset DataReader?
Is there a way to load column data from DataReader to List? Or maybe there is other way how I can replace DataTable in this example?
You can read value from multiple columns by specifying its index like this
int totalColumns = reader.FieldCount;
for(int i=0;i<totalColumns;i++)
{
var label = reader.GetValue(i);
}
You can select value of all columns by looping through columns.
GetValue takes int as argument which is index of column not the index of row.
The problem is in your for loop. At first when your i is 0, You have initialized a 'Series` object S. After that,
while (reader.Read())
will read your entire Reader while your i will still be zero. SO only the
if(i == 0)
condition will return true and your entire reader will be spent. Afterwards, for i >= 1,
while (reader.Read())
will always return false keeping your array, arrSeries blank. Remove the while loop and directly read value from the dataReader using the index,
reader.GetValue(i);

c#: sql request performance issue

I am accessing a database with c#. Now I have to make some calculations with data that I get from some tables and write it into other existing tables. This works quite good in most cases, but for complex operations it takes a huge amount of time. Now I want to know what would be good practice to speed up my querys and get to my results. Here is what I do:
I get a data table that contains 3 values (lom(unique id), laktanfang, laktende) that contains about 700 rows.
For each row in this table I do a query from another table. This results in another data table containing 2 values (lom(unique id), behanddatum)
Now I check if the the value of behanddatum is in between laktanfang and laktende --> yes: Add the row to the data table that gets returned by my function --> no: go on
In the end I have to get the number of positive results from my data table
Here is the code I currently use. I hope it's not too confusing.
public DataTable HoleAbgeschlosseneLaktationenMitDiagnosen(DateTime daAnfang, DateTime daEnde, string[] stDiagnosen = null)
{
DataTable dtRet = new DataTable();
dtRet.Columns.Add("lom", typeof(string));
dtRet.Columns.Add("laktanfang", typeof(DateTime));
dtRet.Columns.Add("laktende", typeof(DateTime));
DataTable dtAbgänge = HoleAbgängeVonEinzeltierZugang(daEnde, daAnfang);
//Abgeschlossene Laktationen für abgegegangene Tiere
foreach (DataRow dr in dtAbgänge.Rows)
{
if (dr != null)
{
DateTime daAbgangsdatum = dr.Field<DateTime>("abgangsdatum");
string stLom = dr.Field<string>("lom");
DataTable dtKalbungVorAbgang = HoleLetzteKalbungFuerTier(stLom, daAbgangsdatum);
if (dtKalbungVorAbgang.Rows.Count > 0 && !dtKalbungVorAbgang.Rows[0].IsNull("kalbedatum"))
{
DateTime daKalbedatum = (DateTime)dtKalbungVorAbgang.Rows[0]["kalbedatum"];
int inLaktation = (int)dtKalbungVorAbgang.Rows[0]["laktation"];
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daKalbedatum, daAbgangsdatum) || stDiagnosen == null)
{
DataRow drLaktAbgang = dtRet.NewRow();
drLaktAbgang["lom"] = stLom;
drLaktAbgang["laktanfang"] = daKalbedatum;
drLaktAbgang["laktende"] = daAbgangsdatum;
dtRet.Rows.Add(drLaktAbgang);
}
if (daKalbedatum >= daAnfang && inLaktation > 1)
{
DataTable dtVorherigeKalbung = HoleLetzteKalbungFuerTier(stLom, daKalbedatum.AddDays(-1));
DateTime daVorhKalbung = (DateTime)dtVorherigeKalbung.Rows[0]["kalbedatum"];
if (dtVorherigeKalbung.Rows.Count > 0 && !dtVorherigeKalbung.Rows[0].IsNull("kalbedatum"))
{
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daKalbedatum, daAbgangsdatum) || stDiagnosen == null)
{
DataRow drLaktVorhKalbung = dtRet.NewRow();
drLaktVorhKalbung["lom"] = stLom;
drLaktVorhKalbung["laktanfang"] = daVorhKalbung;
drLaktVorhKalbung["laktende"] = daKalbedatum;
dtRet.Rows.Add(drLaktVorhKalbung);
}
}
}
}
}
}
DataTable dtKalbungen = HoleKalbungenFürLebendTiere(daEnde, daAnfang);
//Abgeschlossene Laktationen für lebende Tiere
foreach (DataRow dr in dtKalbungen.Rows)
{
DateTime daKalbedatumLetzte = dr.Field<DateTime>("kalbedatum");
string stLom = dr.Field<string>("lom");
int inLaktation = dr.Field<int>("laktation");
if (inLaktation > 1)
{
DataTable dtKalbungVorErster = HoleLetzteKalbungFuerTier(stLom, daKalbedatumLetzte.AddDays(-1));
if (!dtKalbungVorErster.Rows[0].IsNull("kalbedatum"))
{
DateTime daKalbedatum = (DateTime)dtKalbungVorErster.Rows[0]["kalbedatum"];
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daKalbedatum, daKalbedatumLetzte) || stDiagnosen == null)
{
DataRow drLaktKalbung = dtRet.NewRow();
drLaktKalbung["lom"] = stLom;
drLaktKalbung["laktanfang"] = daKalbedatum;
drLaktKalbung["laktende"] = daKalbedatumLetzte;
dtRet.Rows.Add(drLaktKalbung);
}
inLaktation = (int)dtKalbungVorErster.Rows[0]["laktation"];
if (daKalbedatum >= daAnfang && inLaktation > 1)
{
DataTable dtVorherigeKalbung = HoleLetzteKalbungFuerTier(stLom, daKalbedatum.AddDays(-1));
if (dtVorherigeKalbung.Rows.Count > 0 && !dtVorherigeKalbung.Rows[0].IsNull("kalbedatum"))
{
DateTime daVorhKalbung = (DateTime)dtVorherigeKalbung.Rows[0]["kalbedatum"];
if (PrüfeObDiagnoseInZeitraumAufgetreten(stLom, stDiagnosen, daVorhKalbung, daKalbedatum) || stDiagnosen == null)
{
DataRow drLaktVorhKalbung = dtRet.NewRow();
drLaktVorhKalbung["lom"] = stLom;
drLaktVorhKalbung["laktanfang"] = daVorhKalbung;
drLaktVorhKalbung["laktende"] = daKalbedatum;
dtRet.Rows.Add(drLaktVorhKalbung);
}
}
}
}
}
}
return dtRet;
}
private bool PrüfeObDiagnoseInZeitraumAufgetreten(string stLom, string[] stDiagnosen, DateTime daAnfang, DateTime daEnde)
{
SqlCommand cmd = new SqlCommand();
DataTable dtDiagnosenGefunden = new DataTable();
cmd.CommandText = "SELECT diagnose " +
"FROM b_milch_hms_diagnose " +
"WHERE lom=#lom AND behanddatum >= #datumanfang AND behanddatum <= #datumende";
if (stDiagnosen != null)
{
int i = 0;
foreach (string st in stDiagnosen)
{
if (st != "")
{
if (i == 0)
cmd.CommandText += " AND diagnose LIKE #gesuchte_diagnose" + i;
else
cmd.CommandText += " OR diagnose LIKE #gesuchte_diagnose" + i;
cmd.Parameters.AddWithValue("#gesuchte_diagnose" + i, st + "%");
}
i++;
}
}
cmd.Parameters.AddWithValue("#lom", stLom);
cmd.Parameters.AddWithValue("#datumanfang", daAnfang);
cmd.Parameters.AddWithValue("#datumende", daEnde);
dtDiagnosenGefunden = w_milch.FühreSqlAus(cmd);
if (dtDiagnosenGefunden.Rows.Count > 0 && !dtDiagnosenGefunden.Rows[0].IsNull("diagnose"))
return true;
return false;
}
I hope you can help me to improve this function to work more efficient or at least give me some hints.
Thanks in advance
You have created a N+1 problem. One way to solve this would be to change HoleAbgängeVonEinzeltierZugang so that it joins in the data you need from the b_milch_hms_diagnose table.
If you are using .NET 4.0, you can also try to use parallel foreach and see the impact it has on the loop execution time. (This is a more general advice you could apply to many examples)
_dtAbgänge.Rows.AsParallel().ForEach(dr=>
{
//do work
});

Unable to modify a dataset before binding to gridview in asp.net

I need to modify a dataset before binding it to a gridview.
When I walk through the complete code block, and hover over dsEmployeeOrg, that records
dont appear modified. What am I missing here?
My code is:
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i].ItemArray[2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i].ItemArray[2] = "0000";
}
}
}
Please modify your code as below
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i][2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i][2] = "0000";
}
}
}

Categories

Resources