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
Related
I have a large List of objects (over 100k rows in a txt file). I have to do some data work with each item in the list I save the object to the database if it doesnt exist and if it does I increase a number column in the for the item and then update the database while saving the updated item.
If I use a regular foreach loop everything works out fine but it takes over 24 hours to finish.
The issue is that when I use a parallel loop the records do not match and sometimes I will get an error on the .Save() method that the item ID was changed.
THIS CODE WORKS
public List<SreckaIsplacena> UpisiUTabeleSerijski (List<SreckaTemp>srt)
{
_srecke = _glavniRepository.UcitajSamoaktivneSrecke().OrderByDescending(item => item.ID).ToList<Srecka>();
List<SreckaIsplacena> pomList = new List<SreckaIsplacena>();
SreckaIsplacena _isplacena;
foreach (SreckaTemp lt in srt)
{
string beznula = lt.sreIspBroj.TrimStart('0');
SreckeDobici srd = new SreckeDobici();
Srecka sr = (from s in _srecke
where s.Sifra == lt.sreSif && s.Serija == lt.sreSerija
select s).First();
List<SreckeDobici> srDob = _glavniRepository.DohvatiSreckeDobiciZaIsplatniBroj(sr, beznula);
if (srDob.Count == 1)
{
srd = srDob.ElementAt(0);
}
List<SreckaNagrade> sreckaNagrade = new List<SreckaNagrade>(_glavniRepository.DohvatiNagradeZaSrecku(sr.ID).OrderBy(item => item.SifraFox));
double iznos = lt.sreIznDob / lt.sreBrDob;
SreckaNagrade nag = (from sn in sreckaNagrade
where sn.Iznos == lt.sreIznDob
select sn).FirstOrDefault();
Odobrenje odo = new Odobrenje();
odo = odo.DohvatiOdobrenje(valutaGlavna.ID, lt.sreIsplatio).FirstOrDefault();
List<PorezSrecka> listaPoreza = _glavniRepository.UcitajPorezSrecka(valutaGlavna, odo, sr, nag.NagradaId);
List<SreckaIsplacena> sveIsplacene = _glavniRepository.DohvatiIsplaceneSreckeZaValutuIProdavacaSreckuNagraduNovo(valutaGlavna.ID, sr.ID, nag.NagradaId, lt.sreIsplatio);
if (sveIsplacene.Count > 1)
{
System.Windows.MessageBox.Show("Greska, ista srecka s istim dobitkom kod istog prodavaca u istoj valuti 2 put nadjena u bazi");
}
else if (sveIsplacene.Count == 1)
{
_isplacena = sveIsplacene.ElementAt(0);
_isplacena.BrojDobitaka = _isplacena.BrojDobitaka + lt.sreBrDob;
_isplacena.Update();
var index = pomList.FindIndex(r => r.ID == _isplacena.ID);
if (index != -1)
{
pomList[index] = _isplacena;
}
}
else if (sveIsplacene.Count==0)
{
_isplacena = new SreckaIsplacena();
decimal iz = Convert.ToDecimal(lt.sreIznDob);
_isplacena.BrojDobitaka = lt.sreBrDob;
_isplacena.Iznos = iz;
_isplacena.Nagrada = nag;
_isplacena.Prodavac = lt.sreIsplatio;
_isplacena.Valuta = valutaGlavna;
_isplacena.Srecka = sr;
_isplacena.Cijena = Convert.ToDecimal(sr.Cijena);
if (listaPoreza.Count == 1)
{
PorezSrecka ps = listaPoreza.ElementAt(0);
_isplacena.SreckaPorez = ps;
}
_isplacena.Save();
int ispID = _isplacena.ID;
if (ispID != 0)
{
srd.Sre_isplatio = lt.sreIsplatio;
srd.Sre_valuta = valutaGlavna;
srd.Update();
}
pomList.Add(_isplacena);
}
}
return pomList;
}
THIS CODE DOES NOT WORK
public List<SreckaIsplacena> UpisiSamoUTabele(ConcurrentBag<SreckaTemp> srt)
{
_srecke = _glavniRepository.UcitajSamoaktivneSrecke().OrderByDescending(item => item.ID).ToList<Srecka>();
List<SreckaIsplacena> pomList = new List<SreckaIsplacena>();
SreckaIsplacena _isplacena;
Parallel.ForEach(srt, (lt) =>
{
string beznula = lt.sreIspBroj.TrimStart('0');
SreckeDobici srd = new SreckeDobici();
Srecka sr = (from s in _srecke
where s.Sifra == lt.sreSif && s.Serija == lt.sreSerija
select s).First();
List<SreckeDobici> srDob = _glavniRepository.DohvatiSreckeDobiciZaIsplatniBroj(sr, beznula);
if (srDob.Count == 1)
{
srd = srDob.ElementAt(0);
}
List<SreckaNagrade> sreckaNagrade = new List<SreckaNagrade>(_glavniRepository.DohvatiNagradeZaSrecku(sr.ID).OrderBy(item => item.SifraFox));
SreckaNagrade nag = (from sn in sreckaNagrade
where sn.Iznos == lt.sreIznDob
select sn).FirstOrDefault();
Odobrenje odo = new Odobrenje();
odo = odo.DohvatiOdobrenje(valutaGlavna.ID, lt.sreIsplatio).FirstOrDefault();
List<PorezSrecka> listaPoreza = _glavniRepository.UcitajPorezSrecka(valutaGlavna, odo, sr, nag.NagradaId);
List<SreckaIsplacena> sveIsplacene = _glavniRepository.DohvatiIsplaceneSreckeZaValutuIProdavacaSreckuNagraduNovo(valutaGlavna.ID, sr.ID, nag.NagradaId, lt.sreIsplatio);
if (sveIsplacene.Count == 1)
{
_isplacena = sveIsplacene.ElementAt(0);
lock (_isplacena)
{
_isplacena.BrojDobitaka = _isplacena.BrojDobitaka + lt.sreBrDob;
_isplacena.Update();
var index = pomList.FindIndex(r => r.ID == _isplacena.ID);
if (index != -1)
{
pomList[index] = _isplacena;
}
}
}
else if (sveIsplacene.Count==0)
{
_isplacena = new SreckaIsplacena();
decimal iz = Convert.ToDecimal(lt.sreIznDob);
_isplacena.BrojDobitaka = lt.sreBrDob;
_isplacena.Iznos = iz;
_isplacena.Nagrada = nag;
_isplacena.Prodavac = lt.sreIsplatio;
_isplacena.Valuta = valutaGlavna;
_isplacena.Srecka = sr;
_isplacena.Cijena = Convert.ToDecimal(sr.Cijena);
lock(_isplacena)
{
if (listaPoreza.Count == 1)
{
PorezSrecka ps = listaPoreza.ElementAt(0);
_isplacena.SreckaPorez = ps;
}
_isplacena.Save();
int ispID = _isplacena.ID;
if (ispID != 0)
{
srd.Sre_isplatio = lt.sreIsplatio;
srd.Sre_valuta = valutaGlavna;
srd.Update();
}
pomList.Add(_isplacena);
}
}
});
return pomList;
}
I tried using ConcurrentBag instead of List but ran into an issue because ConcurrentBag does not have the FindIndex method (var index = pomList.FindIndex(r => r.ID == _isplacena.ID);). I know there is some way to take out the object and put back in but not sure how to do that and from what I read Lists should be ok if you use locking which I am.
Please help.
I want to create a group of registered clients using different products, categories and sub categories.
I am using asp.net C# and updating database using entity model.
int PID = Convert.ToInt32(ddProduct.SelectedValue);
if (isValidName(txtGroupName.Text))
{
if (ddBusinessCategory.SelectedValue == "0")
{
var clients = db.Client_Master.Where(c => c.InquiredFor == PID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = null;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
else
{
if (ddSubCategory.SelectedValue == "0")
{
int CID = Convert.ToInt32(ddBusinessCategory.SelectedValue);
var clients = db.Client_Master.Where(c => c.InquiredFor == PID && c.BusinessCategory == CID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = CID;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
else
{
int CID = Convert.ToInt32(ddBusinessCategory.SelectedValue);
int SID = Convert.ToInt32(ddSubCategory.SelectedValue);
var clients = db.Client_Master.Where(c => c.InquiredFor == PID && c.BusinessCategory == CID && c.SubCategory == SID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = CID;
gobj.SubCatID = SID;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
}
Groups();
}
I tried to add Group ID using many ways but didn't succeed.
Please suggest me how can I solve this.
Thank you !!
You should create new table ClientsProducts, which will have reference to Client ID and Product ID. This is called One-to-Many Relationships.
You can read here about this here.
I Solved this by taking the ID of last data of list and save as a group ID so, with the help of this we get unique group ID.
if (ddBusinessCategory.SelectedValue == "0")
{
var clients = db.Client_Master.Where(c => c.InquiredFor == PID).ToList();
int GrpID = 0;
if (clients.Count() > 0)
{
foreach (var clt in clients)
{
if (ProductGrp(PID, clt.CID))
{
Group_Master gobj = new Group_Master();
gobj.GrpID = 0;
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = null;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
GrpID = gobj.GID;
}
else
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "myscript()", "bootbox.alert({title: '<b>Error</b>',message: '<b>Group already exist.</b>',});", true);
break;
}
}
List<Group_Master> ggobj = db.Group_Master.Where(g => g.ProductID == PID && g.CatID == null && g.SubCatID == null).ToList();
foreach (var gid in ggobj)
{
if (gid.GrpID == 0)
{
Group_Master gmobj = db.Group_Master.Single(s => s.GID == gid.GID);
gmobj.GrpID = GrpID;
db.SaveChanges();
}
}
}
else
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "myscript()", "bootbox.alert({title: '<b>Error</b>',message: '<b>No Clients exist.</b>',});", true);
}
}
I am developing the my asp.net project, I'm try to make ASP.net text box for Auto Generate code, but its not working correctly, sample Auto Generate code = ID1.
I'm try to use this part,
string txt = txtBatchNo.Text;
txtBatchNo.Text = "C" + Convert.ToInt32(txt.Substring(1, txt.Length - 1)) + 1;
Code:
protected void btnAdd_Click(object sender, EventArgs e)
{
int newId = 1;
if (selectGRNDetailId == -1)
{
{
try
{
if (dtFabricItem.Rows.Count > 0)
{
newId = Convert.ToInt32(dtFabricItem.Rows[dtFabricItem.Rows.Count - 1]["GRNDetailsID"].ToString()) + 1;
}
}
catch (Exception)
{
newId = 1;
}
}
}
else
{
newId = selectGRNDetailId;
}
if (dtFabricItem == null)
{
CreateFabricDetails();
dtFabricItem = dt;
}
else
{
CreateFabricDetails();
}
DataRow dr2 = null;
dr2 = dt.NewRow();
dr2["GRNDetailsID"] = newId;
dr2["GRNDetailID"] = selectGRNId;
dr2["BatchNO"] = txtBatchNo.Text;
dr2["ItemId"] = Convert.ToInt32(ddlYarnName.SelectedValue);
dr2["ItemName"] = ddlYarnName.SelectedItem.Text;
dr2["LotId"] = Convert.ToInt32(ddlLotNo.SelectedValue);
dr2["LotName"] = ddlLotNo.SelectedItem.Text;
dr2["FibetLot"] = txtFiberLot.Text;
dr2["ContainsNo"] = txtContainsNO.Text;
dr2["Shade"] = txtShade.Text;
dr2["Quantity"] = Convert.ToDecimal(txtQty.Text).ToString();
dr2["YarnPrice"] = Convert.ToDecimal(txtYarnPrice.Text).ToString();
dr2["Cornweight"] = Convert.ToDecimal(txtCornWeight.Text).ToString();
dr2["BoxWeight"] = Convert.ToDecimal(txtBoxWeight.Text).ToString();
dr2["NumberofCones"] = Convert.ToDecimal(txtNumberofcones.Text).ToString();
dr2["Numberofboxes"] = Convert.ToDecimal(txtNumberofboxes.Text).ToString();
dt.Rows.Add(dr2);
//txtNumberofcones.Text = (Convert.ToDecimal(txtBoxWeight.Text) / Convert.ToDecimal(txtCornWeight.Text)).ToString();
if (dtFabricItem == null || dtFabricItem.Rows.Count == 0)
{
dtFabricItem = dt;
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
}
else
{
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.Merge(dt);
}
//dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.AcceptChanges();
gvrItemDetails.DataSource = dtFabricItem;
gvrItemDetails.DataBind();
selectGRNDetailId = -1;
ClearDetails();
}
TextBox Id = `txtBatchNo`
I am using Visual Studio 2015 and Entity Framework 6. I am trying to add entries from inputted information into multiple tables.
This is what I have so far:
protected void btnOrder_Click(object sender, EventArgs e)
{
using (FlowerCompanyEntities flower = new FlowerCompanyEntities())
{
int rFlowers = 0;
Boolean rVase = false;
DateTime DeliveryDate = DateTime.Parse(tbDelivery.Text);
string flowerArrangement = ddlListFlowers.SelectedValue;
if (flowerArrangement == "f2")
{
rFlowers = 1;
}
if (flowerArrangement == "f3")
{
rFlowers = 2;
}
if (flowerArrangement == "f1")
{
rFlowers = 3;
}
if (flowerArrangement == "f4")
{
rFlowers = 4;
}
if (flowerArrangement == "f5")
{
rFlowers = 5;
}
string vase = rbList.SelectedItem.Value.ToString();
if (vase == "NO")
{
rVase = false;
}
if (vase == "YES")
{
rVase = true;
}
Customers cust = new Customers();
Addresses Addr = new Addresses();
Phone Pho = new Phone();
Delivery Del = new Delivery();
Arrangements arr = new Arrangements();
OrderStatus ordstat = new OrderStatus();
Orders ord = new Orders();
Pho.Phone1 = tbPhone.Text;
Addr.Street = tbStreet.Text;
Addr.City = tbCity.Text;
Addr.States = tbState.Text;
Addr.Zip = tbZip.Text;
cust.FirstName = tbFirstName.Text;
cust.LastName = tbLastName.Text;
Del.DeliverDate = DeliveryDate;
arr.FlowerID = rFlowers;
ordstat.OrderStatus1 = tbStatus.Text;
ord.Vase = rVase;
ord.OrderMessage = tbOrderMessage.Text;
try {
flower.Phone.Add(Pho);
flower.Addresses.Add(Addr);
flower.Customers.Add(cust);
flower.Delivery.Add(Del);
flower.Arrangements.Add(arr);
flower.OrderStatus.Add(ordstat);
flower.Orders.Add(ord);
flower.SaveChanges();
Response.Redirect("Orders.aspx");
}
catch { }
}
However, on the button click i get an exception error. I also just realized that some of those tables -- with those entries would need the foreign key of the other tables put in.
Question: How do I add all these entries to my database when there is multiple tables and foreign keys?
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";
}
}
}