Search code examples
asp.net-mvcentity-frameworkentity-framework-6asp.net-identity

Cannot insert NULL into column 'UserId'


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**
        },

Solution

  • 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)
        {
        }
    }