Search code examples
c#asp.netdatabaseentity-frameworkasp.net-web-api

EF SaveChanges not saving and not throwing exception


I have a method that creates a new user and then insert a row in the User Permission table, but nothing is happening. Here is my code:

// before: creates user

var permission = new UserPermission()
{
    UserId = user.Id,
    UserName = user.UserName,
    Assets = createUserModel.Assets
};

AccountDb.UserPermissions.Add(permission);
var saveChangesResult = AccountDb.SaveChanges();

if (saveChangesResult == 0) // the result is always 0
{
    AppUserManager.Delete(user);
    return BadRequest("User permission could not be saved");
}

// then: add user to role and return ok

SaveChanges always returns 0 and doesn't update the database, I've already googled for it and tried the following actions:

// no success
AccountDb.UserPermissions.Attach(permission);

// no success either
AccountDb.Entry(permission).State = EntityState.Added;

And I tried in async method too, but no luck. Here is my "UserPermission" model:

public class UserPermission
{
    public int Id { get; set; }

    public string UserId { get; set; }

    public string UserName { get; set; }

    public string _Assets { get; set; }

    [NotMapped]
    public List<int> Assets
    {
        get
        {
            if (_Assets == null) return null;
            return Array.ConvertAll(_Assets.Split(';'), Int32.Parse).ToList();
        }
        set
        {
            _Assets = String.Join(";", value.Select(x => x.ToString()).ToArray());
        }
    }
}

It's curious because this method was working lately, but after some changes in "AccountContext" and some rolebacks, I notice that the method wasn't working anymore.

-- edit --

here is the full create method

[HttpPost]
[Route("create")]
public IHttpActionResult CreateUser(CreateUserBindingModel createUserModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (createUserModel.RoleName is null)
    {
        return BadRequest("There is no role assigned to user");
    }

    var user = new UserModel()
    {
        UserName = createUserModel.UserName,
        Email = createUserModel.Email,
        FirstName = createUserModel.FirstName,
        LastName = createUserModel.LastName
    };

    var addUserResult = AppUserManager.Create(user, createUserModel.Password);

    if (!addUserResult.Succeeded)
    {
        return GetErrorResult(addUserResult);
    }

    var permission = new UserPermission()
    {
        UserId = user.Id,
        UserName = user.UserName,
        Assets = createUserModel.Assets
    };

    AccountDb.UserPermissions.Add(permission);
    var saveChangesResult = AccountDb.SaveChanges();

    if (saveChangesResult == 0)
    {
        AppUserManager.Delete(user);
        return BadRequest("User permission could not be saved");
    }

    var addRoleResult = AppUserManager.AddToRole(user.Id, createUserModel.RoleName);

    if (!addRoleResult.Succeeded)
    {
        AppUserManager.Delete(user);
        return GetErrorResult(addUserResult);
    }

    return Ok(TheModelFactory.Create(user));
}

-- edit 2 --

I was using an Azure db string and I changed to a local db string, but the problem still is the same, UserPermissions Table does not update and no error is emiting.


Solution

  • I found a solution!

    For some reason, my local instance of AccountContext was the problem, it gets all UserPermissions but doesn't update. So I created a new instance and tried to add the permission:

    using (var db = new AccountContext())
    {
         db.UserPermissions.Add(permission);
         var saveChangesResult = db.SaveChanges();
    
         if (saveChangesResult == 0)
         {
             AppUserManager.Delete(user);
             return BadRequest("User permission could not be saved");
         }
    }  
    

    now it's working well. But I don't know why the local AccountDb is not working now if it was working in the past