I have 3 tables: Companies, Subcontracts, and CompanyToSubcontract
The CompanyToSubcontract table is the guid of the Company and guid of the Subcontract. I have a MultiSelectList on the Subcontract Edit and Create views where the user can select multiple companies. I finally got it working where it displays the correct companies as selected in the Subcontract Edit view. I'm not having an issue with saving the data.
In the create view, the subcontract doesn't have a guid until it's written to the Sql database, so how can I get the guid to save to the CompanyToSubcontract table?
Also, in the edit view, I'm doing something wrong. It doesn't save.the company selections. I also need to delete records for companies which are unselected. What is the best way to go about doing that?
I followed the NerdDinner tutorial to get my basic structure and now I'm trying to update to fulfill my needs.
Anyone who can point me in the right direction?
In SubcontractRepository:
public void Save()
{
db.SubmitChanges();
}
In Controller:
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult Edit(string id, FormCollection formValues)
{
// Retrieve existing subcontract
subcontract subcontract = subcontractRepository.GetSubcontract(id);
if (subcontract == null)
return View("NotFound");
else
{
try
{
UpdateModel(subcontract);
IEnumerable<Guid> selectedCompanies = Request.Form["Companies"].Split(new Char[] { ',' }).Select(idStr => new Guid(idStr));
foreach (var item in selectedCompanies)
{
CompanyToSubcontract cs = new CompanyToSubcontract();
cs.subcontract_id = subcontract.subcontract_id;
cs.company_id = item;
subcontractRepository.Save();
}
subcontract.lastupdate_date = DateTime.Now;
subcontract.lastupdatedby_user = User.Identity.Name;
//Persist changes back to database
subcontractRepository.Save();
//Perform HTTP redirect to details page for the saved subcontract
return RedirectToAction("Details", new { id = subcontract.subcontract_no });
}
catch
{
ModelState.AddRuleViolations(subcontract.GetRuleViolations());开发者_运维技巧
return View(new SubcontractFormViewModel(subcontract));
}
}
}
In the selectedCompanies foreach
loop, change:
cs.subcontract_id = subcontract.subcontract_id;
to:
cs.subcontract = subcontract;
The reason why this works is explained in detail in my response to this question. In addition, LINQ-to-SQL also manages the assignment of primary keys and their propagation to foreign keys automatically. When you call db.SubmitChanges()
, it recognizes that if the subcontract object doesn't have a foreign key assigned, it treats it as an INSERT change. Also, since the subcontract object is being associated with a CompanyToSubcontract object, it knows to update the foreign key field in the association entity with the primary key value it just assigned to the Subcontract entity.
精彩评论