【问题标题】:"Cannot insert the value NULL into column " but my column is Nullable... Entity Framework 5 asp.net MVC“无法将值 NULL 插入列”但我的列是 Nullable ... Entity Framework 5 asp.net MVC
【发布时间】:2013-04-12 01:23:20
【问题描述】:

我用 asp.net MVC 互联网应用程序开始了一个项目...... 我对默认代码进行了一些更改... 我创建了自己的用户上下文:

public class UsersDBContext : DbContext
{

    public DbSet<UserProfile> UserProfiles { get; set; }

我对 AccountModel 做了一些更改:

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int? test { get; set; }

}

我添加了此列测试。如您所见,此列可以为空..... 但是在运行时,当我尝试注册用户时出现此错误:

无法将值 NULL 插入列“test”。列不允许空值。插入失败。

错误发生在这一行:

WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

有人知道解决办法吗?

编辑:迁移代码:

    public override void Up()
    {
        AlterColumn("dbo.UserProfile", "test", c => c.Int());
    }

public override void Down()
    {
        AlterColumn("dbo.UserProfile", "test", c => c.Int(nullable: false));
    }

【问题讨论】:

  • 在实体中使用什么数据类型并不重要。如果数据库列本身不可为空,它将失败。
  • 我已经更新了数据库...
  • @ZeCariocaSilva,这听起来不像你更新到数据库。您能否向我们展示您在 SSMS 中的数据库(或描述的结果)以确认它实际上已更新为允许该列上的空值?

标签: c# asp.net-mvc entity-framework


【解决方案1】:

对数据库进行更改后,您是否更新了实体框架 edmx?我发现有时在进行更改后使用 edmx 设计器中的更新功能效果不佳。我会从 edmx 设计器中删除该表,然后重新添加它,然后重新构建您的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2016-04-18
    • 2013-02-27
    • 2021-10-31
    相关资源
    最近更新 更多