【问题标题】:Cannot insert NULL into column 'UserId'无法将 NULL 插入“UserId”列
【发布时间】:2020-06-26 08:40:30
【问题描述】:

我正在使用实体框架和这个模型:

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

我收到这个错误

在执行 update-database 命令时,无法将 NULL 插入到“UserId”表 AspNetUsers 列中

下面是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**
        },

【问题讨论】:

  • 我认为这与实体框架无关,您的数据库中的“UserId”列必须允许空值。

标签: asp.net-mvc entity-framework entity-framework-6 asp.net-identity


【解决方案1】:

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

试试吧,或许能解决你的问题。

public class ApplicationUser : IdentityUser
{
}



public class CustomContext : IdentityDbContext<ApplicationUser>
{

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

【讨论】:

    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多