.net core identity user id comes different from database

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

Question

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
{

    [Key]
    [Column("TABLEID")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override string Id { get; set; }

    [Required]
    [Column("AD")]
    public string Name { get; set; }

    [Required]
    [Column("SOYAD")]
    public string Surname { get; set; }

    [Required]
    [Column("AKTIF")]
    public bool IsActive { get; set; }

    [Required]
    [Column("SIL")]
    public bool IsDeleted { get; set; }

    [Required]
    [Column("KAYITTARIHI")]
    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)
    {

        base.OnModelCreating(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.
        builder.Entity<IdentityUser>().ToTable("TBLKULLANICI");
        builder.Entity<IdentityRole>().ToTable("TBLROL");
        builder.Entity<IdentityUserRole<string>>().ToTable("TBLKULLANICIROL");
        builder.Entity<IdentityRoleClaim<string>>().ToTable("TBLROLECLAIM");
        builder.Entity<IdentityUserClaim<string>>().ToTable("TBLUSERCLAIM");
        builder.Entity<IdentityUserLogin<string>>().ToTable("TBLUSERLOGIN");
        builder.Entity<IdentityUserToken<string>>().ToTable("TBLUSERTOKEN");

        // Custom models.
        builder.Entity<Vehicle>().ToTable("TBLARAC");
        builder.Entity<VehicleImage>().ToTable("TBLARACRESIM");
        builder.Entity<TransportAdvertise>().ToTable("TBLNAKLIYEILAN");
        builder.Entity<TransportRequest>().ToTable("TBLNAKLIYEISTEK");
        builder.Entity<TransportRoute>().ToTable("TBLROTA");
        builder.Entity<City>().ToTable("TBLSEHIR");

        // FK mappings..
        builder.Entity<Vehicle>()
                .HasOne(v => v.User)
                .WithMany(u => u.Vehicles)
                .HasForeignKey(v => v.UserId)
                .HasConstraintName("FK_VEHICLE_USER");

        // Vehicle image model fks.
        builder.Entity<VehicleImage>()
                .HasOne(vi => vi.Vehicle)
                .WithMany(v => v.Images)
                .HasForeignKey(vi => vi.VehicleId)
                .HasConstraintName("FK_VEHICLE_IMAGE_VEHICLE");

        builder.Entity<VehicleImage>()
                .HasOne(vi => vi.User)
                .WithMany(u => u.VehicleImages)
                .HasForeignKey(vi => vi.UserId)
                .HasConstraintName("FK_VEHICLE_IMAGE_USER");

        // TransportAdvertise model fks.
        builder.Entity<TransportAdvertise>()
                .HasOne(ta => ta.User)
                .WithMany(u => u.TansportAdvertises)
                .HasForeignKey(ta => ta.UserId)
                .HasConstraintName("FK_TRANSPORT_ADS_USER");

        builder.Entity<TransportAdvertise>()
                .HasOne(ta => ta.Vehicle)
                .WithMany(v => v.TransportAdvertises)
                .HasForeignKey(ta => ta.VehicleId)
                .HasConstraintName("FK_TRANSPORT_ADS_VEHICLE");

        // TransportRequest model fks.
        builder.Entity<TransportRequest>()
                .HasOne(tr => tr.User)
                .WithMany(u => u.TransportRequests)
                .HasForeignKey(tr => tr.UserId)
                .HasConstraintName("FK_TRANSPORT_RQST_USER");

        builder.Entity<TransportRequest>()
                .HasOne(tr => tr.TransportAdvertise)
                .WithMany(ta => ta.TransportRequests)
                .HasForeignKey(tr => tr.TransportAdvertiseId)
                .HasConstraintName("FK_TRANSPORT_RQST_ADS");

        // TransportRoute model fks.
        builder.Entity<TransportRoute>()
                .HasOne(tr => tr.City)
                .WithMany(c => c.TransportRoutes)
                .HasForeignKey(tr => tr.CityId)
                .HasConstraintName("FK_TRANSPORT_ROUTE_CITY");

        builder.Entity<TransportRoute>()
                .HasOne(tr => tr.TransportAdvertise)
                .WithMany(ta => ta.TransportRoutes)
                .HasForeignKey(tr => tr.TransportAdvertiseId)
                .HasConstraintName("FK_TRANSPORT_ROUTE_ADS");

    }

Vehicle Creation Code

[HttpPost]
    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
        };

        _vehicleService.AddNew(vehicle);

        return RedirectToAction("Index");
    }
1
0
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

0
7/30/2017 12:01:43 PM


Related Questions





Related

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