'ASP.NET Core 3.0 - Can't Update-Database
I just created the project using the command dotnet new angular -o <output_directory_name> -au Individual
and scaffold identity then I installed Microsoft.EntityFrameworkCore.SqlServer but when I run the command update-database, I get the error below.
Failed executing DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [AspNetRoles] (
[Id] TEXT NOT NULL,
[Name] TEXT(256) NULL,
[NormalizedName] TEXT(256) NULL,
[ConcurrencyStamp] TEXT NULL,
CONSTRAINT [PK_AspNetRoles] PRIMARY KEY ([Id])
);
and then at the end end another error
Error Number:2716,State:1,Class:16
Column, parameter, or variable #2: Cannot specify a column width on data type text.
Below is the generated CreateIdentitySchema
migration
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
ApplicationDbContextModelSnapshot.cs
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
How to fix this errors so I can update-database?
Changing 'TEXT' to 'VARCHAR' in 00000000000000_CreateIdentitySchema.Designer.cs resulted in the following error. The same happens when I change it to 'NVARCHAR'
Data type 'VARCHAR' for property 'Id' is not supported in this form. Either specify the length explicitly in the type name, for example as 'NVARCHAR(16)', or remove the data type and use APIs such as HasMaxLength to allow EF choose the data type.
Solution 1:[1]
I had this error and it can be fixed as follows.
Open up the project and delete 2 migration files and 1 snapshot file. Most likely named 0000...InitialCreate.cs, 0000...InitialCreate.Designer.cs and the ...DbContextModelSnapshot.cs. Leave the DbContextClass.
Delete the database.
Use dotnet to create a new migration and update the database. I also script the migration to check it.
dotnet ef migrations add InitialCreate --context ApplicationDbContext -v
dotnet ef database update --context ApplicationDbContext -v
dotnet ef migrations script --context ApplicationDbContext -v
Solution 2:[2]
These answers were all helpful, especially the one from @klent. I had generated a new project using:
dotnet new angular -o [MY PROJECT] -au Individual
This produced a new project that used Sqlite as the data provider, although I wasn't aware of that. I changed the connection string to my SQL Server, then ran:
dotnet ef database update
and got the error posted in the original question. After reviewing the answers here I realized that I had the incorrect data provider, and the migrations were targeting Sqlite syntax, which was using TEXT(256) for one of the column specifications. So my specific steps to correct were to:
- Remove the Microsoft.EntityFrameworkCore.Sqlite Nuget package.
- Install the Microsoft.EntityFrameworkCore.SqlServer Nuget package.
- In the ConfigureServices method of my Startup.cs, change the
services.AddDbContext
call to useoptions.UseSqlServer
instead ofoptions.UseSqlite
. - Remove the _CreateIdentitySchema and ApplicationDbContentsModelSnapshot classes from the Migrations folder.
- After ensuring the connection string in AppSettings.json points to the SQL Server and not Sqlite, run
dotnet ef migrations add CreateIdentitySchema -o Data\Migrations
. Note that the output folder specified in the-o
parameter may be different for you. - Check the Visual Studio Project Explorer. Two new classes should now appear in the Migrations folder.
- Run
dotnet ef database update
. This will create the tables in the database noted in the connection string.
Additionally, if you want your tables to be in a specific schema, for example "Auth", open your ApplicationDbContext class and add:
protected override void OnModelCreating( ModelBuilder builder )
{
base.OnModelCreating( builder );
builder.HasDefaultSchema( "Auth" );
}
However, this will set the schema for all access that uses this DbContext. It wasn't a problem for me since I'm not using EF for my application data, just Identity data. YMMV.
Solution 3:[3]
As already answered by a few others the default Identity installation seems to create the wrong column types; namely that some of the Id columns should be varchar and not text.
I had exactly the same issues as you and spent ages trying to effectively solve it.
The quickest way I found to solve it, and for anyone else coming across this problem, is to:
- Create the new project
- Delete the Migrations folder completely
- Install the package for Sql Server (Or whatever data system you're using) and connection string details
- Add your own migration using
dotnet ef migrations add <MIGRATION NAME>
orAdd-Migration
(this will write new migration designer files from scratch with the correct column structure - Lastly, update your database with
dotnet ef database update
orUpdate-Database
Solution 4:[4]
As per comments from @sepupic and @PeterSmith, the problem was that the auto-generated code in 00000000000000_CreateIdentitySchema.Designer.cs
had TEXT
fields with HasMaxLength
so I changed it to VARCHAR
then I added HasMaxLength(450)
to all VARCHAR
Ids then I tried to update-database again and it worked.
I run the project and tried to Register a user and I got the error below
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Bolean'
Since I still had errors I did the following:
- I deleted the generated table then created a new project with the command
dotnet new angular -o <output_directory_name> -au Individual
- I didn't scaffold new identity to the newly created project
- I copied the db name from my previous project and run the command update-database
- There were two missing tables
DeviceCodes
andPersistedGrants
so I run the commandadd-migration
but it didn't generate anything so I copied the migration code of the two tables from my previous project and pasted it the empty migration code I created earlier. - I run the project again and register a new user and it finally worked
I still don't know why I got errors since the project I did before didn't have any problem with the auto-generated code.
Solution 5:[5]
I had an error like yours as
Column 'Id' in table 'Roles' is of a type that is invalid for use as a key column in an index.
Because I changed the table names those are coming with Individual Identity of Asp.Net Core web application.
To put it simply,
- Delete everything in Migrations Folder apart from ApplicationDBContext.
- Add-Migration
- Make sure if your tables names are matching in Up, Down and BuildTargetModel
- Then update-database
It worked for me!
Edit : My main point is that make sure if your tables names are matching in Up, Down and BuildTargetModel. After that update-database will work.
Solution 6:[6]
I resolved this database update error with the first answer by @abCsharp, but not until I noticed that the project, which I started with the option of Identity, had created a new migrations folder under the project folder. The original migrations folder was under a Data folder that also contained the ApplicationDbContext.
I deleted the original folder (for cleanliness) and ran the newly created migration which worked. I also deleted the migrations history table in the database, which contains tables for which I am not using migrations.
FWIW All the data types for text in all the tables are nvarchar.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Venrix |
Solution 2 | Bob Mc |
Solution 3 | OllyF |
Solution 4 | |
Solution 5 | Emre Kadan |
Solution 6 | JaneH |