I began with the following tables; one for staff names, and one for salutations:
public class PrmTbl_Salutation
{
public int ID { get; set; }
public string Desc { get; set; }
public bool Active { get; set; }
public PrmTbl_Salutation(int id, string desc, Boolean active)
{
ID = id;
Desc = desc;
Active = active;
}
public PrmTbl_Salutation() { }
}
public class PrmTbl_Staff
{
public int ID { get; set; }
public int SalutationID { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public PrmTbl_Staff(int id, int salID, string name, Boolean active)
{
ID = id;
SalutationID = salID;
Name = name;
Active = active;
}
public PrmTbl_Staff() { }
public PrmTbl_Salutation Salutation { get; set; }
}
I had individual Views for each table, but wanted to combine them so that a staff name would be preceded by their relevant salutation. The View would include an editable list of current staff as a form, with another form to insert a new staff record. This is the ViewModel:
public class StaffSalutation
{
public int StaffID { get; set; }
public string Name { get; set; }
public string Salutation { get; set; }
public int SalutationID { get; set; }
public bool Active { get; set; }
public List<PrmTbl_Salutation> SaltsList { get; set; }
}
The update functionality works fine:
PrmTbl_Staff thisRow = staffDB.PrmTbl_Staffs.Find(id);
string tempName = Convert.ToString(UpdateArray[thisName]);
Boolean tempActive = Boolean.Parse(UpdateArray[thisActive]);
int tempSalID = Convert.ToInt32(UpdateArray[thisSalID]);
thisRow.Name = tempName;
thisRow.Active = tempActive;
thisRow.SalutationID = tempSalID;
staffDB.SaveChanges();
... but the insert fails
string tempName = Convert.ToString(staff["name"]);
int tempSalID = Convert.ToInt32(staff["saltID"]);
PrmTbl_Staff thisRecord = new PrmTbl_Staff(0, tempSalID, tempName, true);
staffDB.PrmTbl_Staffs.Add(thisRecord); //FAILS HERE
staffDB.SaveChanges();
return RedirectToAction("Staff");
with the error The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.PrmTbl_Staff_dbo.PrmTbl_Salutation_SalutationID". The conflict occurred in database "LibraryBase2.DAL.LibraryContext", table "dbo.PrmTbl_Salutation", column 'ID'.
The statement has been terminated.
This is my first time using ViewModels. There appears to be an ambiguity or conflict regarding the Salutation ID and the new Staff ID. What am I doing wrong? Any help greatly appreciated.