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

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

Question

Asp.net Identity's IdentityUser class is something I'm trying to modify.

public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        IsBlocked = false;
    }

    public bool IsBlocked { get; set; }
}

The issue is that the additional field is produced nullable while using code first migrations. same if I delete and recreate the database.

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 do I correct this?

In other classes on the same DbContext, I have boolean fields, and none of them were generated with a null value (as they should).

1
3
10/24/2013 12:41:47 PM

Accepted Answer

The initial response, below, presupposed that you had an abstract base class and were using TPC or, if you specified the base class, TPT.[Table] property instead of TPH on the actual class.

In contrast, if you use a non-abstract base class and don't include a[Table] to youApplicationUser , and as a result, yourApplicationUser and IdentityUser You are utilizing the TPH scenario if your maps to a single table. Any fields from a subclass in your single table will be nullable in this case. Changing to TPC or TPT is the only method to reverse this.

original response

Your property should have the [Required] attribute:

[Required]
public bool IsBlocked { get; set; }

Then you should migrate to make it aNON NULL column.

However, this will cause problems if your table already contains data because it won't know what default value to create. In this instance, I first update the migration to turn it into aNULL execute a Sql command to set the desired settings, followed by a AlterColumn command to make it aNON 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