无法将 NULL 插入列 'UserId'

Cannot insert NULL into column 'UserId'

我正在使用 Entity Framework 并且这个型号:

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; }
}

这是我正在使用的上下文

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

我遇到了这个错误

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

下面是Seed方法中USER的对象:-

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

如果您要使用 Asp.Net 身份, 首先,您的 CustomContext 应该继承自 IdentityDbContext class 而不是 DbContext。其次,你的 User class 应该继承自 IdentityUser class.

试一试,应该能解决你的问题。

public class ApplicationUser : IdentityUser
{
}



public class CustomContext : IdentityDbContext<ApplicationUser>
{

    public CustomContext(DbContextOptions<CustomContext> options)
        : base(options)
    {
    }
}