我正在尝试插入数据。我正在插入一个新公司,该公司有一个新的公司联系人分支机构。首先是架构。注意CompanyBranch和CompanyContact之间的多对多关系。我的问题是 CompanyContact 中的CompanyBranchID总是最终为0 ,而不是指定的CompanyBranchId。正确插入公司和分支数据。可能是关系不正确?
[HttpPost]
public ActionResult CreateCompany(FormCollection formData)
{
CompanyContact contact = new CompanyContact()
{
ContactName = formData["ContactName"],
eMail = formData["Email"],
LandLine = formData["LandLine"],
Mobile = formData["Mobile"],
Role = formData["Role"]
};
CompanyBranch branch = new CompanyBranch()
{
BranchAddress1 = formData["BranchAddress1"],
BranchAddress2 = formData["BranchAddress2"],
BranchAddress3 = formData["BranchAddress3"],
BranchAddress4 = formData["BranchAddress4"],
BranchAddress5 = formData["BranchAddress5"]
};
branch.CompanyContacts.Add(contact);
Company newCompany = new Company()
{
Name = formData["CompanyName"]
};
newCompany.Branches.Add(branch);
newCompany.Branches[0].Company = null;
newCompany.Branches[0].Students = null;
db.Entry(newCompany).State = EntityState.Added;
db.SaveChanges();
return RedirectToAction("Edit", "Student", new { id = int.Parse(formData["StudentId"]) });
}