Updating through LINQ in different DataBase - c#

I have a DB which looks like this:
1st:
CommissionsV2 (Table = Entity_Product_Point)
This is my DBML too which has only one table.
2nd:
WebEnroll (Table = PlanMaster)
This is my another DBML which has one table in it.
Now through LINQ I am adding a row in this which has a query like this:
CommissionsV2DataContext cv = new CommissionsV2DataContext();
Entity_Product_Point ev = new Entity_Product_Point();
ev.Entity_ID = getEntity;
ev.Product_ID = tr.First();
ev.HiCommissionOld = (double)firststYrComp;
ev.LowCommissionOld = (double)recurringComp;
ev.HiCommission = (double)finalFirstYrComp * 100;
ev.LowCommission = (double)finalRecurringComp * 100;
ev.DateCreated = System.DateTime.Now;
cv.Entity_Product_Points.InsertOnSubmit(ev);
cv.SubmitChanges();
Now my update statement is like this:
protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Getting the Entity_ID from the Session!
int getEntity = Int16.Parse(Session["EntitySelected"].ToString());
//Accessing the variables from the controls!
System.Web.UI.WebControls.TextBox product_ID = gvShowComm.Rows[e.RowIndex].FindControl("ProductName") as System.Web.UI.WebControls.TextBox;
System.Web.UI.WebControls.TextBox planName = gvShowComm.Rows[e.RowIndex].FindControl("PlanName") as System.Web.UI.WebControls.TextBox;
System.Web.UI.WebControls.TextBox hiCommOld = gvShowComm.Rows[e.RowIndex].FindControl("HiComm") as System.Web.UI.WebControls.TextBox;
System.Web.UI.WebControls.TextBox lowCommOld = gvShowComm.Rows[e.RowIndex].FindControl("LowComm") as System.Web.UI.WebControls.TextBox;
//Storing the values into variables!
int product = Int16.Parse(product_ID.Text);
string plan = planName.Text;
int hiOld = Int16.Parse(hiCommOld.Text);
int lowOld = Int16.Parse(lowCommOld.Text);
//Updating the values into the table through LINQ!
dbWebEnrollDataContext dt = new dbWebEnrollDataContext(); //This has PlanName in PlanMaster Table.
CommissionsV2DataContext cv = new CommissionsV2DataContext(); //Entity_Product_Point has all the other columns which needs to be updated!
Entity_Product_Point ev = cv.Entity_Product_Points.Single(c => c.Product_ID == product);
ev.HiCommissionOld = hiOld;
ev.LowCommissionOld = lowOld;
ev.Entity_ID = getEntity;
cv.SubmitChanges();

In order to update, you need to retrieve the entity that needs to be updated.
So in your case it would be:
Entity_Product_Point ev = cv.Entity_Product_Points.Single(c => c.Product_ID == product);
ev.HiCommissionOld = hiOld;
ev.LowCommissionOld = lowOld;
// Retrieve the plan that needs to be updated and set the name
// Submit the changes
cv.SubmitChanges();
// Retrieve the new values and rebind the gridview against the new values

Related

Unable to show two or more data rows in the gridview when binding with the List

When the add button is clicked second time, there is supposed to be two lines of data rows in the GridView ( the first row is the first click and the second row is the newly added data). However there is only one data row.
List<DonationReceivedItem> drList = new List<DonationReceivedItem>();
protected void lbnAdd_Click(object sender, EventArgs e)
{
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
}
Try changing the following code:
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
to:
DonationReceivedItem temp = new DonationReceivedItem();
drList = gvNonExpired.DataSource;
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
See if that makes a difference :)
Because you are creating a new list you are wiping the previous data. First instantiate the list with the old data, then add the new data.

DataBind into DB from Class in asp.net

I'm filling up a database from an aspx web application.
Everything works fine, except for the fact that I use multiple pages for users to fill in their data into DB.
So, i got this method in one class.cs file:
public class Botones
{
public void SaveCVInfo2(string varOne,string varTwo, string varThree)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
This is just a part of the file, it has more columns, but it doesn't change the example.
However, I added another class.cs file in order to reference it's method from a button in the second page. Just like the one I posted before in this post:
public class Botones2
{
public void SaveCVInfo3(string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
AS you can see there are more columns I'm filling into the db, in the same table, problem is, when i submit data to the sql server, from second page, it just creates a new Usuario_web without the columns i referenced in first class.
What i need is to bind somehow the data already sent from first page. So first class is associated with all other classes, and columns are filled in the same row.
If anybody knows how to handle this situation, please let me know.
EDIT
This is how i call methods from asp buttons:
protected void Button1_Click(object sender, EventArgs e)
{
Botones botones = new Botones();
botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
}
And SaveCVInfo3:
protected void Button1_Click(object sender, EventArgs e)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
CAUTION: Untested code below.
I would return the columna.ID from SaveCVInfo2:
public int SaveCVInfo2(string varOne,string varTwo, string varThree)
{
int columnaId = 0;
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
columnaId = columna.ID;
}
return columnaId;
}
And call the method, get the ID and save in the Session like this:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
Botones botones = new Botones();
columnaId = botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
Session["columnaId"] = columnaId.ToString();
}
Now when calling the SaveCVInfo3 method, I can pass the columnaId:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
if(Session["columnaId"] != null && int.TryParse(Session["columnaId"].ToString(), out columnaId)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(columnaId, nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
}
And in SaveCVInfo3 method I would get the object by Id, which is already saved in previous page and edit it, save it:
public void SaveCVInfo3(int columnaId, string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
//You will need to add reference to Linq if not added already
//Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
//db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
EDIT If Id is not a primary key, you can change this part-
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
to :
Usuario_Web columna =(Usuario_Web)db.Usuario_Web.Where(x=>x.ID == columnaId).FirstOrDefault()

Can't populate database table

protected void ButtonAddDatabase_Click(object sender, EventArgs e)
{
using (KnowItCvdbEntities db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmplDbSkill = (
from p
in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
_emp = theEmplDbSkill;
if (_emp != null)
{
foreach (var vItem in ListBoxDatabases.Items)
{
if (ValueAlreadyInListDb(vItem))
return;
}
//Get existing skilllevel from db
var skillLevel = (from sL in db.TECHNICAL_SKILL_LEVEL
where sL.technical_skill_level_id == Convert.ToInt32(DropDownListDB.SelectedValue)
select sL).FirstOrDefault();
//Get existing skillvalue from db
var skillValue = (from sV in db.TECHNICAL_SKILLS
where sV.technical_skill_id == Convert.ToInt32(RadioButtonListDatabase.SelectedValue)
select sV).FirstOrDefault();
//Adding to employees_technical_skills table
var empSkill = new EMPLOYEES_TECHNICAL_SKILLS
{
technical_skill_id = Convert.ToInt32(DropDownListDB.SelectedItem.Value),
TECHNICAL_SKILLS = skillValue,
technical_skill_level_id = Convert.ToInt32(RadioButtonListDatabase.SelectedItem.Value)
TECHNICAL_SKILL_LEVEL = skillLevel,
employee_id = _emp.employee_id
}
_emp.EMPLOYEES_TECHNICAL_SKILLS_Add(empSkill);
db.SaveChanges();
_emp.EMPLOYEES_TECHNICAL_SKILLS.Add(empSkill);
db.SaveChanges();
}
}
}
Right now I'm working on populating the following table:
This is my tables:
But I keep getting the error:
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
Regards,
Kristian.
It looks like the Entity framework can't convert Convert.ToInt32() to an SQL expression. I would convert the radiobutton and dropdown values to int in memory first, then pass them to the queries:
int TechnicalSkillLevelID = int.Parse(DropDownListDB.SelectedValue);
int TechnicalSkillID = int.Parse(RadioButtonListDatabase.SelectedValue);
//Get existing skilllevel from db
var skillLevel = (from sL in db.TECHNICAL_SKILL_LEVEL
where sL.technical_skill_level_id == TechnicalSkillLevelID)
select sL).FirstOrDefault();
//Get existing skillvalue from db
var skillValue = (from sV in db.TECHNICAL_SKILLS
where sV.technical_skill_id == TechnicalSkillID)
select sV).FirstOrDefault();
//Adding to employees_technical_skills table
var empSkill = new EMPLOYEES_TECHNICAL_SKILLS
{
technical_skill_id = skillValue.technical_skill_id,
TECHNICAL_SKILLS = skillValue,
technical_skill_level_id = skillLevel.technical_skill_level_id)
TECHNICAL_SKILL_LEVEL = skillLevel,
employee_id = _emp.employee_id
}
Also, since you already pulled back the skill levels and skill values, no need to grab the values from the drop down / radio button list. Just use the skillValue and skillLevel objects.

Entity Framework add first row to database from a List?

foreach (StockItem item in StockList)
{
Master master = new Master();
master.VoucherNo = BillNo;
master.Voucher = "Sales";
master.StockName = StockList[0].StockName;
master.Quantity = StockList[0].Quantity;
master.Unit = StockList[0].Unit;
master.Price = StockList[0].UnitPrice;
master.Amount = StockList[0].Amount;
dbContext.AddToMasters(master);
dbContext.SaveChanges();
}
Sale sale = new Sale();
sale.InvoiceNo = BillNo;
sale.Date = BillDate;
sale.Party = Customer;
sale.Amount = (decimal)TotalAmount;
dbContext.AddToSales(sale);
dbContext.SaveChanges();
This code add only the first row from StockList for all n times if there are n rows.
What wrongs with the code?
You are iterating over StockList, but you aren't actually using the iteration variable.
Everywhere that you use StockList[0], you should be using item.
Edit: Here is what your loop should look like:
foreach (StockItem item in StockList)
{
Master master = new Master();
master.VoucherNo = BillNo;
master.Voucher = "Sales";
master.StockName = item.StockName;
master.Quantity = item.Quantity;
master.Unit = item.Unit;
master.Price = item.UnitPrice;
master.Amount = item.Amount;
dbContext.AddToMasters(master);
dbContext.SaveChanges();
}

c# set DataContext column values without strongly typing it

//Instead of the this
var tableX = db.PRODUCT; //db is the DataContext
//I can do the below (Thanks to http://stackoverflow.com/questions/1919632/get-table-data-from-table-name-in-linq-datacontext
string tablename = "PRODUCT";
var table = (ITable)db.GetType().GetProperty(tablename).GetValue(db, null);
//But instead of this
PRODUCT _Product = new PRODUCT();
_Product.PRD_CODE = "code1";
_Product.PRD_DESC = "description1";
table.InsertOnSubmit(_Product);
db.SubmitChanges();
//How can I do something like this
string tablename = "PRODUCT";
var table = (ITable)db.GetType().GetProperty(tablename).GetValue(db, null);
string lsColumnPrdCode = "PRD_CODE";
string lsColumnPrdDesc = "PRD_DESC";
table _tableInstance = new table();
_tableInstance[lsColumnPrdCode] = "code1";
_tableInstance[lsColumnPrdDesc] = "description1";
_tableInstance.InsertOnSubmit(_tableInstance);
db.SubmitChanges();
So it is possible to set datacontext column values without strongly typing it?
Of cause you can use reflection to do that kind of stuff. Maybe something similar to this code:
Type productType = Type.GetType("PRODUCT");
var product = Activator.CreateInstance(productType);
productType.GetProperty("PRD_CODE").SetValue(product, "code1");
productType.GetProperty("PRD_DESC").SetValue(product, "description1");
Type tableType = table.GetType();
tableType.GetMethod("InsertOnSubmit").Invoke(table, new object[] {product});
But why do you want to do that?

Categories

Resources