I am trying to add two records to two separate entities using one action result.
My data is passing just fine, and no catches are met (implying that the database is saving the necessary changes and returning the appropriate Ok).
My two entities are related, one entity is linked to the other through a Foreign Key. The entities are created in such a way that the entity dependent on the other (for its foreign key) is created after the other.
The first entity (Branch) is created and is stored just fine as expected on the SQL Server. However, the second is not, and I am not sure why?
Both entities are set to auto-increment their primary keys.
My action result (within my web API is split into two separate methods):
// Create New Branch
[HttpPost]
[Route("CreateBranch")]
public ActionResult CreateBranch([FromBody] BranchesVM newBranch)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var branch = new Branch
{
BranchName = newBranch.branch.BranchName,
BranchContactNumber = newBranch.branch.BranchContactNumber,
BranchEmailAddress = newBranch.branch.BranchEmailAddress,
BranchImage = newBranch.branch.BranchImage,
BranchStatus = true
};
db.Branch.Add(branch);
db.SaveChanges();
var latestBranchRecordReader = db.Branch.OrderByDescending(x => x.BranchId).First();
var latestBranchRecord = latestBranchRecordReader.BranchId;
var branchAddress = new BranchAddress
{
BranchStreetName = newBranch.address.BranchStreetName,
BranchSuburb = newBranch.address.BranchSuburb,
BranchCity = newBranch.address.BranchCity,
BranchProvince = newBranch.address.BranchProvince,
BranchCountry = newBranch.address.BranchCountry,
BranchZip = newBranch.address.BranchZip,
BranchDate = DateTime.Now,
BranchLate = newBranch.address.BranchLate,
BranchLng = newBranch.address.BranchLng,
BranchId = branch.BranchId
};
CreateBranchAddress(branchAddress);
return Ok();
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
public ActionResult CreateBranchAddress(BranchAddress newBranchAddress)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
db.BranchAddress.Add(newBranchAddress);
db.SaveChanges();
return Ok();
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
Both db.SaveChanges() are hit when debugging, so I do not understand why nothing is being added to the database for the BranchAddress entity.
The data coming through newBranch of type BranchesVM is also correct (I get no POST 400 errors).
Are there any other possible reasons as to why it may not be adding?