Home > Mobile >  In WebAPI POST method how to pass Id which is set to Uniqueidentifier in database ASP.NET?
In WebAPI POST method how to pass Id which is set to Uniqueidentifier in database ASP.NET?

Time:12-29

I have a Users table in database, its Id PK is set to Uniqueidentifier. Now using the Web API I am adding a new user through postman into database. when I add the first record it adds the user into database but for adding further records its not allowing me to add because a unique id is not getting generated. On internet I have found that I can use GUID for that purpose but unable to find that how I can pass it in my controller using Linq. here is my Post method for adding new user that I am using:

[HttpPost]
public async Task<IHttpActionResult> AddNewUser([FromBody]  User user)
{              
    try
    {
        using (var newuser = new hospiceEntities())
        {
            newuser.Users.Add(new User()
            {
                id = user.Id,
                UserName = user.UserName,
                PasswordHash = user.PasswordHash,
                Discriminator = user.Discriminator,
                ApplicationId = user.ApplicationId,
                LoweredUserName = user.LoweredUserName,
                IsAnonymous = user.IsAnonymous,
                Email = user.Email,
                IsApproved = user.IsApproved,
                IsLockedOut = user.IsLockedOut,
                CreateDate = user.CreateDate,
                FailedPasswordAnswerAttemptCount = user.FailedPasswordAnswerAttemptCount,
                IsTempPassword = user.IsTempPassword,
                LockoutCount = user.LockoutCount,
                AccessFailedCount = user.AccessFailedCount,
                LockoutEnabled = user.LockoutEnabled
            }); ;
            newuser.SaveChanges();
            return Ok(Helper.SuccessResponse());
            // await newuser.SaveChangesAsync();
        }
    }
    catch (Exception ex) {
        return BadRequest(Helper.ErrorResponse(ex.Message));
    }    
}

The first record being entered into database is as below:

enter image description here

CodePudding user response:

try this

try
    {
        user.Id=Guid.NewGuid();

        using (var newuser = new hospiceEntities())
        {
            newuser.Users.Add(user);
            
           await newuser.SaveChangesAsync();

            return Ok(Helper.SuccessResponse());
           
        }
    }
    catch (Exception ex) {
        return BadRequest(Helper.ErrorResponse(ex.Message));
    }    
}
  • Related