0

我正在尝试插入数据。我正在插入一个新公司,该公司有一个新的分支机构,该分支机构有一个新的公司联系人。首先是架构。注意 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"]) });
    }
4

0 回答 0