在 asp.net Identity 中自定义 IdentityUser 类时会创建可空字段 [英] Nullable fields are created when customizing IdentityUser class in asp.net Identity
问题描述
我正在尝试在 asp.net 身份中自定义 IdentityUser 类.
I am trying to customize IdentityUser class in asp.net identity.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
IsBlocked = false;
}
public bool IsBlocked { get; set; }
}
问题是:当使用代码优先迁移时,附加字段被创建为可空的.如果我删除数据库并重新创建它,也是如此.
The problem is: when using code first migrations, the additional field is created nullable. The same if I drop database and recreate it.
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (128) NOT NULL,
[UserName] NVARCHAR (MAX) NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[IsConfirmed] BIT NOT NULL,
[IsBlocked] BIT NULL,
[Discriminator] NVARCHAR (128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
我该如何解决这个问题?
How can I fix this?
我在同一个 DbContext 上的其他类中有布尔字段,并且它们都是创建的,而不是 null(应该如此).
I have boolean fields in other classes on the same DbContext, and they are all created not null (as they should).
推荐答案
下面的原始答案假设您有一个抽象基类,因此使用 TPC,如果您指定了 [Table],则可能使用 TPT
属性,而不是 TPH.
The original answer, below, assumed you had an abstract base class, and therefore were using TPC, or possibly TPT if you specified the [Table]
attribute on the concrete class, rather than TPH.
但是,如果您使用的是非抽象基类并且未在 ApplicationUser
上指定 [Table]
,因此您的 ApplicationUser
和 IdentityUser
映射到单个表,那么您正在使用 TPH 方案.在这种情况下,子类中的任何字段在您的单个表中都可以为空.改变这种情况的唯一方法是切换到 TPC 或 TPT.
However, if you are using a non-abstract base class and do not specify a [Table]
on your ApplicationUser
, and therefore your ApplicationUser
and IdentityUser
map to a single table, then you are using the TPH scenario. In this scenario any fields from a subclass will be nullable in your single table. The only way to change this is to switch to TPC or TPT.
原答案
把 [必需]
属性上的属性:
Put the [Required]
attribute on your property:
[Required]
public bool IsBlocked { get; set; }
然后,您的迁移应使其成为 NON NULL
列.
Your migration should then make it a NON NULL
column.
但是,如果您的表中已经有数据,这将导致问题,因为它不知道要创建什么默认值.在这种情况下,我编辑迁移以首先使其成为 NULL
列,然后运行 Sql
命令设置我想要的值,然后AlterColumn
使其成为 NON NULL
列
However, if you already have data in your table this will cause issues as it won't know what default value to create. In this case I edit the migration to first make it a NULL
column, then run a Sql
command to set the values I want, and then AlterColumn
make it a NON NULL
column
AddColumn("dbo.MyTable", "MyColumn", c => c.Boolean());
Sql("UPDATE MyTable SET MyColumn = 1");
AlterColumn("dbo.MyTable", "MyColumn", c => c.Boolean(nullable: false));
这篇关于在 asp.net Identity 中自定义 IdentityUser 类时会创建可空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!