.net core identity user id comes different from database

.net asp.net-mvc core entity-framework-core identity


I am trying to get current user's id with identity in .NET Core. Managed to create new user and login with it but whenever loging in with same user identity returns different guid.

I have a product entity which stores userId as foreign key. Whenever I try to add new product it throws error becouse given userId is not in user table.

But I register a new user and go add new product immediately it works. Lists products. Hovewer, logout and login again with same user, products are not listed. When I debug it saw that the _userManager.GetUserId(User) returning a different value.

Why could it be happened?

How can I fix this?

UPDATE My User Creation Code

var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
    await _signInManager.SignInAsync(user, isPersistent: false);

    return RedirectToAction(nameof(HomeController.Index), "Home");

My User Login Code

var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);

if (result.Succeeded)
    return RedirectToLocal(returnUrl);

Here is My ApplicationUser Model Class

public class ApplicationUser : IdentityUser

    public override string Id { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }

    public bool IsActive { get; set; }

    public bool IsDeleted { get; set; }

    public DateTime RecordDate { get; set; }

    public List<Vehicle> Vehicles { get; set; }
    public List<VehicleImage> VehicleImages { get; set; }
    public List<TransportAdvertise> TansportAdvertises { get; set; }
    public List<TransportRequest> TransportRequests { get; set; }


Here is My DbContext

public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<Vehicle> Vehicles { get; set; }
    public DbSet<VehicleImage> VehicleImages { get; set; }
    public DbSet<TransportAdvertise> TransportAdvertises { get; set; }
    public DbSet<TransportRequest> TransportRequests { get; set; }
    public DbSet<TransportRoute> TransportRoutes { get; set; }
    public DbSet<City> Cities { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)

        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        // Identity built-in models.

        // Custom models.

        // FK mappings..
                .HasOne(v => v.User)
                .WithMany(u => u.Vehicles)
                .HasForeignKey(v => v.UserId)

        // Vehicle image model fks.
                .HasOne(vi => vi.Vehicle)
                .WithMany(v => v.Images)
                .HasForeignKey(vi => vi.VehicleId)

                .HasOne(vi => vi.User)
                .WithMany(u => u.VehicleImages)
                .HasForeignKey(vi => vi.UserId)

        // TransportAdvertise model fks.
                .HasOne(ta => ta.User)
                .WithMany(u => u.TansportAdvertises)
                .HasForeignKey(ta => ta.UserId)

                .HasOne(ta => ta.Vehicle)
                .WithMany(v => v.TransportAdvertises)
                .HasForeignKey(ta => ta.VehicleId)

        // TransportRequest model fks.
                .HasOne(tr => tr.User)
                .WithMany(u => u.TransportRequests)
                .HasForeignKey(tr => tr.UserId)

                .HasOne(tr => tr.TransportAdvertise)
                .WithMany(ta => ta.TransportRequests)
                .HasForeignKey(tr => tr.TransportAdvertiseId)

        // TransportRoute model fks.
                .HasOne(tr => tr.City)
                .WithMany(c => c.TransportRoutes)
                .HasForeignKey(tr => tr.CityId)

                .HasOne(tr => tr.TransportAdvertise)
                .WithMany(ta => ta.TransportRoutes)
                .HasForeignKey(tr => tr.TransportAdvertiseId)


Vehicle Creation Code

    public IActionResult AddNewVehicle(VehicleViewModel model)
        var id = _userManager.GetUserId(User);

        // model property check needs to be done before.
        // vehicle table does not accept nulls.

        var vehicle = new Vehicle()
            Model = model.Model,
            Capacity = model.Capacity,
            Description = model.Description,
            Year = model.Year,
            Active = true,
            Delete = false,
            RecordDate = DateTime.Now,
            UserId = id


        return RedirectToAction("Index");
7/30/2017 1:53:21 PM

Popular Answer

Do a simple experiment... Create a new user and note its Id... Immediately add a product and check again if the user ID has changed after the save operation. It is possible the user details is being mutated/changed upon save operation. You can also paste the code samples for creating a user, creating a product and retrieving a user here. The problem is most likely where u are saving the vehicles. At that point the user details is either being mutated, or the vehicles is being stored with a different user. The vehicles has a 1 to 1 relationship with the user. So when creating a vehicle be careful not to be doing vehicle.user = new User; Ensure you are doing the following. 1- Get the user from the Db :

var user = await UserManager.FindByIdAsync("Id of currently logged in user");

2- set vehicle.user to the user retrieved above:

vehicle.user = user.

You can share code where u are saving vehicle for people to be able to help. Also you can prevent the user Id from being automatically generated in the db and add a [Required] attribute on the Id field. You can the do

user.Id = Guid.Guid.NewGuid()

. This can help prevent issues where a new user is automatically added to the db when u create a vehicle

7/30/2017 12:01:43 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow