问题
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?
I have boolean fields in other classes on the same DbContext, and they are all created not null (as they should).
回答1:
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.
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.
Original answer
Put the [Required] attribute on your property:
[Required]
public bool IsBlocked { get; set; }
Your migration should then make it a NON NULL column.
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));
来源:https://stackoverflow.com/questions/19566258/nullable-fields-are-created-when-customizing-identityuser-class-in-asp-net-ident