2

I am create small demo for user registration using web api mvc c#.i am register Succeeded for user using 'Register' in web api.now i want to using this method also edit this user by id so how can do that i don't know any one know please let me know. i my code i will manage add/edit call in one method so i will first check the condition on id is null then add and id is not null then go for the edit but how can edit this record and role.

here this my method :

  [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {            
        try
        {
            if (model.Id == "")
            {          
              //here is for add user method         
                var user = new ApplicationUser() { UserName = model.Email, Email = model.Email,PhoneNumber = model.PhoneNumber };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var UsersContext = new ApplicationDbContext();
                    var res = UsersContext.Users.Where(x => x.UserName == user.UserName).FirstOrDefault();
                    var UserId = res.Id;
                    await UserManager.AddToRoleAsync(UserId, model.UserRole);
                    return Ok(result);
                }
                return Ok(result);
            }
            else
            {
               //here i want write edit code
                var UsersContext = new ApplicationDbContext();
                var Team = UsersContext.Users.Find(model.Id);

                Team.UserName = model.UserName;
                Team.Email = model.Email;
                Team.PhoneNumber = model.PhoneNumber;
                IdentityResult result = await UserManager.UpdateAsync(Team); //here getting error.
                return Ok(result);  
            }                
            return Ok("Done");
        }
        catch (Exception ex)
        {                
        }
        return Ok();
    }  
3
  • @Bansanta Matia have you any idea how can edit user? Commented Apr 5, 2017 at 7:56
  • What error you are getting in update ? Commented Apr 5, 2017 at 8:04
  • Attaching an entity of type 'abc.Models.ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are newand have not yet received database-generated key values. In this case use the 'Add' method orthe 'Added' entity state to track the graph and then set the state of non-new entities to'Unchanged' or 'Modified' as appropriate. Commented Apr 5, 2017 at 8:07

1 Answer 1

1

UPDATED:

First check whether you are passing values to all required field or not.

Keep this UserStore after your controller class calling braces {.

[Authorize]
public class AccountController : Controller
{
 UserStore<IdentityUser> myUserStore = new UserStore<IdentityUser>(new 
                                    ApplicationDbContext());
 //rest code

Then inside your Register() Post method, do like this bellow,

if (model.Id == "")
 {
  //Add new user code
 }
else
 {
  var context = myUserStore.Context as ApplicationDbContext;
  var Team = context.Users.Find(model.Id);
  //change the field value what ever you want to update
  context.Users.Attach(Team);
  context.Entry(Team).State = EntityState.Modified;
  context.Configuration.ValidateOnSaveEnabled = false;
  await context.SaveChangesAsync();
  return Ok("Updated");
 }

Hope it helps :)

Sign up to request clarification or add additional context in comments.

8 Comments

"UserManager" is a class?
Write like this new UserManager<ApplicationUser>(userStore); Let me know whether it's working or not
still getting same : 'Attaching an entity of type 'abc.Models.ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are newand have not yet received database-generated key values. In this case use the 'Add' method orthe 'Added' entity state to track the graph and then set the state of non-new entities to'Unchanged' or 'Modified' as appropriate.'
hi i am try with your solution but still getting same error can you please know how can resolved this error
np :) await context.SaveChangesAsync(); here i m getting error 'cannot implicitly convert type 'int' to 'Microsoft.AspNet.identity.IdenetituyResult' '
|

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.