0

Is it necessary to use TransactionScope when using entity framework? Following article suggest TransactionScope is not needed at all.

https://coderwall.com/p/jnniww/why-you-shouldn-t-use-entity-framework-with-transactions

In my current application I'm using Transactions in the following manner which causes high CPU in database server. Can I get rid of TransactionScope? and still expect the records to save to the database only if all the inserts suceeded when there are multiple tables involved?

public string AddNewCustomRole(CustomRoleViewModel customRole)
{
    using (TransactionScope scope = new TransactionScope())
    {

        CustomRole role = new CustomRole()
        {
            CreatedOnUtc = DateTime.UtcNow,
            CustomRoleName = customRole.CustomRoleName,
            LastModifiedUtc = DateTime.UtcNow,
            CompanyId = customRole.CompanyId,
            CreatedBy = customRole.UserId,
            LastModifiedBy = customRole.UserId,
            IsAdmin = false,
            Ref = Guid.NewGuid()

        };

        _context.CustomRole.Add(role);

        var result = _context.CustomRolePermission;

        foreach (var item in result)
        {
            CustomRoleRolepermission permission = new CustomRoleRolepermission()
            {
                RolePermissionId = item.RolePermissionId,
                CustomRoleId = role.CustomRoleId
            };

            _context.CustomRoleRolepermission.Add(permission);
        }

        _context.SaveChanges();

        scope.Complete();

        return role.Ref.ToString();
    }

}
chamara
  • 12,649
  • 32
  • 134
  • 210
  • Summary of that article - 'TransactionScope defaults to `Serializable`, and I didn't like that'. Read the comments (in the article you posted), and you can see that can easily be changed. https://stackoverflow.com/questions/11292763/why-is-system-transactions-transactionscope-default-isolationlevel-serializable https://mitchwheat.com/2019/01/07/transactionscope-default-isolation-level/ – mjwills Jul 16 '19 at 06:51
  • 1
    Also read the docs https://learn.microsoft.com/en-us/ef/ef6/saving/transactions in particular _What EF does by default_ – Steve Jul 16 '19 at 06:53
  • How many records is your code adding? 1? 50? 20,000? – mjwills Jul 16 '19 at 06:54
  • `Can I get rid of TransactionScope?` Short answer - yes. Read @Steve's link. – mjwills Jul 16 '19 at 06:58
  • You don't need `TransactionScope` , `_context.SaveChanges();` will handle transaction for you. – Ali Bahrami Jul 16 '19 at 07:19

0 Answers0