Cannot insert NULL into column 'UserId'

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

Question

I am using Entity Framework and this model:

public class User
{
    [Key]
    public int id { get; set; }

    [MaxLength(150)]
    public string first_name_1 { get; set; }

    public int? location_id { get; set; }

    [ForeignKey("location_id")]
    public virtual Location location  { get; set; }  

    [MaxLength(50)]
    public string telephone_no_1 { get; set; }

    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual ApplicationUser applicationuser { get; set; }
}

This is the context I am using

public class CustomContext: DbContext
{
    public RegistryContext() : base("name=" + ConfigurationManager.AppSettings["ContextName"])
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<RegistryContext, registry_services.Migrations.Configuration>());
    }

    public System.Data.Entity.DbSet<registry_services.Models.User> Users { get; set; }

    public int GetNextSequenceValue(string sequenceName)
    {
        var rawQuery = Database.SqlQuery<int>($"SELECT NEXT VALUE FOR {sequenceName};");
        var task = rawQuery.SingleAsync();
        int nextVal = task.Result;

        return nextVal;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });

        // Your configuration goes here
    }
}

I am getting this error

Cannot insert NULL into column 'UserId' table AspNetUsers while executing update-database command

Below is the object for USER in the Seed method:-

        new Models.User
        {
            id = 4,
            first_name_1 = "Nick",

            location_id = 3,

            UserId = "67639413-9e42-4eef-9292-bd66527f91bf"**// this is ID of one of the records in AspNetUsers Table**
        },
1
0
3/14/2020 5:50:38 PM

Accepted Answer

If you're going to use Asp.Net Identity, First of all your CustomContext should inherits from IdentityDbContext class instead of DbContext. Secondly, your User class should inherits from IdentityUser class.

Try it, probably resolve your problem.

public class ApplicationUser : IdentityUser
{
}



public class CustomContext : IdentityDbContext<ApplicationUser>
{

    public CustomContext(DbContextOptions<CustomContext> options)
        : base(options)
    {
    }
}
1
3/15/2020 7:32:55 AM


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