RollbackResult<TValue> Class
.NET Standard 2.x
Namespace: SnapObjects.Data.AspNetCore
Assembly: SnapObjects.Data.AspNetCore.dll
Provides a way to return an action result and rolls back the current transaction.
It only works when TransactionAttribute
is applied to the action (or the controller) to start an automatically managed transaction.
Syntax
public class RollbackResult<TValue> : ActionResult, IRollbackResult
Constructors
Name | Description |
---|---|
RollbackResult(ActionResult<TValue> result) | Initializes a new instance of the RollbackResult<TValue> class. |
Methods
Name | Return Type | Description |
---|---|---|
ExecuteResult(ActionContext context) | void | Executes the result operation of the action method synchronously. This method is called by MVC to process the result of an action method. |
ExecuteResultAsync(ActionContext context) | Task | Executes the result operation of the action method asynchronously. This method is called by MVC to process the result of an action method. |
Operators
Name | Return Type | Description |
---|---|---|
Implicit(TValue to RollbackResult<TValue>) | RollbackResult<TValue> | Defines an implicit conversion of a TValue to a RollbackResult. |
Implicit(ActionResult<TValue> to RollbackResult<TValue>) | RollbackResult<TValue> | Defines an implicit conversion of an ActionResult<TValue> to a RollbackResult. |
Examples
The following code demonstrates how to use the Transaction
Attribute in an action of the controller to automatically manage a transaction and use the RollbackResult
object to manually rollback the transaction.
using Appeon.ApiDoc.Models.School;
using Microsoft.AspNetCore.Mvc;
using SnapObjects.Data;
using SnapObjects.Data.AspNetCore;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
namespace Appeon.ApiDoc.RollbackResultExamples
{
public class Action_RollbackResultExamples : ControllerBase
{
SchoolContext _dataContext;
public Action_RollbackResultExamples(SchoolContext dataContext)
{
// Sets the data context.
_dataContext = dataContext;
}
// It uses the `Transaction` Attribute to automatically manage transactions.
[Route("examples/RollbackResultExamples/[action]")]
[HttpPost]
[Transaction]
public ActionResult<int> Example(IEnumerable<IModelEntry<Person>> persons)
{
var mapper = _dataContext.SqlModelMapper;
mapper.TrackRange(persons);
var result = mapper.SaveChanges();
// Rollback when the result is not correct.
if (result.InsertedCount != persons.Count())
{
// It will rollback the transaction.
return new RollbackResult<int>(result.InsertedCount);
}
else
{
return Ok(persons.Count());
}
}
}
}