1

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?

1
  • You have to show Branch and Address classes too. Commented Aug 20, 2021 at 11:31

2 Answers 2

1

Does it need to have 2 ActionResult? If it's possible to have just one, you could try this:

    // 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.Add(branch);
            db.SaveChanges();

            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
            };

            db.Add(branchAddress);
            db.SaveChanges();

            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }                     
    }

You might also want to wrap it using transaction to make sure both query executed successfully, otherwise it will rollback.

    // Create New Branch
    [HttpPost]
    [Route("CreateBranch")]
    public ActionResult CreateBranch([FromBody] BranchesVM newBranch)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        try
        {
            //START TRANSACTION
            using (var transSQL = db.Database.BeginTransaction())
            {
                var branch = new Branch
                {
                    BranchName = newBranch.branch.BranchName,
                    BranchContactNumber = newBranch.branch.BranchContactNumber,
                    BranchEmailAddress = newBranch.branch.BranchEmailAddress,
                    BranchImage = newBranch.branch.BranchImage,
                    BranchStatus = true
                };

                db.Add(branch);
                db.SaveChanges();

                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
                };

                db.Add(branchAddress);
                db.SaveChanges();

                //SQL Commit
                transSQL.commit();

                return Ok();
            }
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Combining the action results into one had a similar result to how it was when having separate ActionResults (Branch added successfully, although BranchAddress did not). However, now I am getting a POST 400 error. Secondly, when wrapped in a transaction, neither worked at all (not Branch nor BranchAddress got added to the DB - although I still received a POST 400 error).
Thank you for suggesting the transaction. This seems to be good practice.
0

I realized that I did not post enough information in my question to get an appropriate answer. However, I changed my catch to output an inner exception:

catch (Exception e)
    {
        return BadRequest(e.InnerException);
    }

This allowed me to see what exactly was causing the error, that being one of the records exceeding its maximum size as set out in the table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.