Noob here.
I'm struggling wrapping my head around a few things. It used to be pretty straightforward to grab some data from a web form and throw it in a database.
I have a view for patient that gathers information when registering the patient. The information lives across multiple tables.
To facilitate this, I've created the following in my patient model:
public class Patient
{
//properties
public virtual PatientCondition patientcondition { get; set; }
public virtual PatientInsurrance patientinsurance { get; set; }
}
This allows me to add fields to my view for each of those models. My view contains fields from both patient and patientinsurrance:
<div class="form-group">
@Html.LabelFor(model => model.patientinsurance.InsuranceCompany, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.patientinsurance.InsuranceCompany, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.patientinsurance.InsuranceCompany, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EmergencyContactPhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmergencyContactPhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.EmergencyContactPhoneNumber, "", new { @class = "text-danger" })
</div>
</div>
When I try to save the patient record, I am getting the following error:
Violation of PRIMARY KEY constraint 'PK_dbo.PatientInsurrances'. Cannot insert duplicate key in object 'dbo.PatientInsurrances'. The duplicate key value is (0).\r\nThe statement has been terminated.
Here is my controller:
public ActionResult Create(Patient patient)
{
if (ModelState.IsValid)
{
db.Patients.Add(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(patient);
}
It is attempting to create a patientinsurancerecord, but it can't because we do not yet know the patientId because we are creating the patient record at this time. Furthermore, patientinsurance is not required and it is possible to create a patient without this patientinsurance.
So the question is, how do I add fields to a view that collect data to be stored in multiple tables?
How do I create foreign key relationships that do not require data for the related table?