Nullable fields are created when customizing IdentityUser class in asp.net Identity

asp.net-identity ef-code-first entity-framework entity-framework-6

Question

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
3
10/24/2013 12:41:47 PM

Accepted Answer

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));
5
10/25/2013 12:06:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow