Referencing a Newly inserted Row's seeded PK in C# Linq
- by Laurence Burke
I want to use the primary key that was just created on the dc.submitchanges() to create a new EmployeeAddress row that references the employee to the address.
protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtZip.Text != "" && txtAdd1.Text != "" && txtCity.Text != "")
{
TestDataClassDataContext dc = new TestDataClassDataContext();
Address addr = new Address()
{
AddressLine1 = txtAdd1.Text,
AddressLine2 = txtAdd2.Text,
City = txtCity.Text,
PostalCode = txtZip.Text,
StateProvinceID = Convert.ToInt32(ddlState.SelectedValue)
};
dc.Addresses.InsertOnSubmit(addr);
lblSuccess.Visible = true;
lblErrMsg.Visible = false;
dc.SubmitChanges();
//
// TODO: insert new row in EmployeeAddress to reference CurEmp to newly created address
//
SetAddrList();
}
else
{
lblErrMsg.Text = "Invalid Input";
lblErrMsg.Visible = true;
}
}
protected void SetAddrList()
{
TestDataClassDataContext dc = new TestDataClassDataContext();
dc.ObjectTrackingEnabled = false;
var addList = from addr in dc.Addresses
from eaddr in dc.EmployeeAddresses
where eaddr.EmployeeID == _curEmpID && addr.AddressID == eaddr.AddressID
select new
{
AddValue = addr.AddressID,
AddText = addr.AddressID,
};
ddlAddList.DataSource = addList;
ddlAddList.DataValueField = "AddValue";
ddlAddList.DataTextField = "AddText";
ddlAddList.DataBind();
ddlAddList.Items.Add(new ListItem("<Add Address>", "-1"));
}