Alan2
Alan2

Reputation: 24562

If one of the multiple adds in a saveChangesAsync fails do the others get added?

I have this function in my application. If the insert of Phrase fails then can someone tell me if the Audit entry still gets added? If that's the case then is there a way that I can package these into a single transaction that could be rolled back.

Also if it fails can I catch this and then still have the procedure exit with an exception?

    [Route("Post")]
    [ValidateModel]
    public async Task<IHttpActionResult> Post([FromBody]Phrase phrase)
    {

        phrase.StatusId = (int)EStatus.Saved;
        UpdateHepburn(phrase);
        db.Phrases.Add(phrase);
        var audit = new Audit()
        {
            Entity = (int)EEntity.Phrase,
            Action = (int)EAudit.Insert,
            Note = phrase.English,
            UserId = userId,
            Date = DateTime.UtcNow,
            Id = phrase.PhraseId
        };
        db.Audits.Add(audit);
        await db.SaveChangesAsync();
        return Ok(phrase);
    }

Upvotes: 4

Views: 1451

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23190

I have this function in my application. If the insert of Phrase fails then can someone tell me if the Audit entry still gets added?

You have written your code in a correct way by calling await db.SaveChangesAsync(); only one time after doing all your modifications on the DbContext.

The answer to your question is: No, the Audit will not be added if Phrase fails. Because you are calling await db.SaveChangesAsync(); after doing all your things with your entities, Entity Framework wil generate all the required SQL Queries and put them in a single SQL transaction which makes the whole queries as an atomic operation to your database. If one of the generated query e.g. Auditgenerated query failed then the transaction will be rolled back. So every modification that have been done to your database will be removed and so Entity Framework will let your database in a coherent state.

Upvotes: 5

Related Questions