Changing column from text to integer with Entity Framework - c#

My table has a text column and I'd like to change to an integer. The existing text column contains values that can be converted to an integer. I don't want to change the column name.
How can I safely do this using code first without losing my data?
One option would be to create a new, temporary column. Copy the values. And then delete the old column and rename the new one. But I'm just not that sure what Entity Framework will decide to do with those changes.

So, I simply changed the column definition from:
[Display(Name = "Bill of Lading")]
[Required]
[StringLength(80)]
public string BillOfLading { get; set; }
To:
[Display(Name = "Bill of Lading")]
public int BillOfLading { get; set; }
I patched up my code so it would compile with the new type, and I added a migration, which looked like this:
public partial class TransloadingDetailBillOfLadingToInt : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "BillOfLading",
table: "TransloadingDetails",
type: "int",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(80)",
oldMaxLength: 80);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "BillOfLading",
table: "TransloadingDetails",
type: "nvarchar(80)",
maxLength: 80,
nullable: false,
oldClrType: typeof(int),
oldType: "int");
}
}
I was able to run update-database on a smaller, demo database we have. On my first attempt, I had a column value that could not be converted. In that instance, I got an error and no data was lost. A good sign!
After correcting the data, I ran it again and the text columns were converted to integers. All the existing data was correctly converted. And then the same thing on my main database.
So, at least in the case of converting a text column to an integer column, where the data can be converted, this works just as you'd want it to work.

Related

Change type of id on column which is also a primary key with a ef migration

I have the following model:
[Key]
public int CustomerSearchConfigId { get; set; }
[Key]
public string CategoryId { get; set; }
[ForeignKey(nameof(CustomerSearchConfigId))]
public CustomerSearchConfig Config { get; set; }
CategoryId is a string, but I have now found out it would need to be an INT.
So I changed the type to an int, ran
dotnet ef migrations add AddFieldsAndRenameFields
Which produced among other this:
migrationBuilder.AlterColumn<int>(
name: "CategoryId",
table: "CustomerSearchConfigTagCategory",
type: "int",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(450)");
But when I run it, I get the following error:
The object 'PK_CustomerSearchConfigTagCategory' is dependent on column 'CategoryId'.
ALTER TABLE ALTER COLUMN CategoryId failed because one or more objects access this column.
When I search around for it, everyone seems to suggest I just delete it all and start over with a completely new migration history and everything..
Which is not an option!
So, does anybody know how I can change the type of CategoryId to an int without having to nuke my tables, migration, data and sanity?
The simple way is to delete the database and build it up again in case you don't have any impairment records.
So if you need to keep all of your information in the database see this guidе
https://www.codeproject.com/Articles/1193009/Changing-primary-key-data-type-in-EF-Core

EFCore roll back migration error: column of invalid type to be used as key column

I'm running into an issue where I'm trying to rollback a migration on a database that already has the migration applied.
This is the error I get:
Failed executing DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [EventStaffRequest] ADD CONSTRAINT [PK_EventStaffRequest] PRIMARY KEY ([Id]);
System.Data.SqlClient.SqlException (0x80131904): Column 'Id' in table 'EventStaffRequest' is of a type that is invalid for use as a key column in an index.
Could not create constraint or index. See previous errors.
ClientConnectionId:29574816-2b1a-4490-a216-a54cd7a2d33b
Error Number:1919,State:1,Class:16
Column 'Id' in table 'EventStaffRequest' is of a type that is invalid for use as a key column in an index.
Could not create constraint or index. See previous errors.
This is the migration I'm trying to rollback:
public partial class AddedCompositeKeyToEventStaffRequest : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest");
migrationBuilder.DropIndex(
name: "IX_EventStaffRequest_EventId",
table: "EventStaffRequest");
migrationBuilder.DropColumn(
name: "Id",
table: "EventStaffRequest");
migrationBuilder.AddPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest",
columns: new[] { "EventId", "QualityTypeId" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest");
migrationBuilder.AddColumn<string>(
name: "Id",
table: "EventStaffRequest",
nullable: false,
defaultValue: "");
migrationBuilder.AddPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest",
column: "Id");
migrationBuilder.CreateIndex(
name: "IX_EventStaffRequest_EventId",
table: "EventStaffRequest",
column: "EventId");
}
}
If it is relevant, this is my model code:
public class EventStaffRequest
{
[Required]
public string EventId { get; set; }
public virtual Event Event { get; set; }
[Required]
public string QualityTypeId { get; set; }
public virtual QualityType QualityType { get; set; }
[Required]
public int AmountRequired { get; set; }
[Required]
public int MinimumRating { get; set; }
}
This migration was created because I decided I needed to change the primary key to be a composite key. I have applied a composite primary key like so in my DbContext (this is what you see in the migration's Up() I guess):
builder.Entity<EventStaffRequest>()
.HasKey(esr => new { esr.EventId, esr.QualityTypeId });
Why is my rollback not succeeding? I don't understand why string is not an appropriate type for key index (I use GUIDs as keys).
There seem to be an issue with migration system. The problem is not the string (of course it can be used for PK), but the maxLength. By default, the string columns have unlimited length, but PK require applying some limit.
Normally when you use string column as PK, even if you don't specify maxLength, EF automatically applies some limit (from what I see, at least for SqlServer it is 450). Interestingly, doing the same what you did in reverse order generates similar migrations with Up and Down content swapped, and the exact same code for AddColumn works. But not when executed in Down method, so there must be a difference (hence a problem) in that path. You might consider posting it in EF Core issue tracker so they know (and eventually fix it).
Anyway, the solution is to explicitly add maxLength parameter to AddColumn call:
migrationBuilder.AddColumn<string>(
name: "Id",
table: "EventStaffRequest",
maxLength: 450,
nullable: false,
defaultValue: "");

Add new Required Field to one of table with EF Code First Migration

I am using EF Code First Migration. I already have lots of data on production Db and I would like to intorduce a non nullable field. How it could be possible?
Currently it throws an error:
The column cannot contain null values. [ Column name = Test,Table name = 'MyTable']
The strategy I generally use for this is to first introduce the new column as optional, populate it, and then make it required. You can actually make separate migration steps by making separate migrations for each of these steps or manually change the automatically generated migration code to make the change all happen in one migration. I will be describing how to use a single migration.
If you add a new [Required] field, the autogenerated migration may look like this which will fail if dbo.MyTable has data in it:
public override void Up()
{
AddColumn("dbo.MyTable", "MyColumn", c => c.String(nullable: false));
}
public override void Down()
{
DropColumn("dbo.MyTable", "MyColumn");
}
You can edit the migration to initially add the column as optional, prepopulate it, and then mark it required. You can use Sql() to perform the prepopulation. Depending on your data, you may desire to calculate the new column’s value based on other columns or even another table and you can do that by writing the appropriate SQL.
public override void Up()
{
AddColumn("dbo.MyTable", "MyColumn", c => c.String());
Sql("UPDATE dbo.MyTable SET MyColumn = COALESCE(SomeOtherColumn, 'My Fallback Value')");
AlterColumn("dbo.MyTable", "MyColumn", c => c.String(nullable: false));
}
public override void Down()
{
DropColumn("dbo.MyTable", "MyColumn");
}
If you merely want to set the same value on all rows, you can skip the Sql() step and add the column as required with a defaultValue before removing the defaultValue. This allows you to set all rows to the same value during migration while still requiring you to manually specify the value when adding new rows. This approach supposedly doesn’t work on older versions of EF. I’m not sure which version of EF is required, but it should at least work on modern ones (≥6.2):
public override void Up()
{
AddColumn("dbo.MyTable", "MyColumn", c => c.String(defaultValue: "Some Value", nullable: false));
}
public override void Down()
{
DropColumn("dbo.MyTable", "MyColumn");
}
You can add a defaultValue in the migration file something like this:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "MyColumn",
table: "dbo.MyTable",
nullable: false,
defaultValue: "");
}
And if the column is bool so you just put the defaultValue false or true depend on your need.
In EFCore 3.1 you can just add the required attribute and it automatically sets a default value
Boolean defaults to false
[Required]
public Boolean myField {get;set;}
Integer defaults to 0
[Required]
public int myField {get;set;}
String defaults to ""
[Required]
public string myField {get;set;}

Entity Framework Code first making a column non-nullable

I am using EF code first for my project. I have following code in my DataModel
[HiddenInput(DisplayValue = false)]
public DateTime? PasswordDate { get; set; }
To make this non-nullable I removed '?' and ran Add-Migration command from Package manager console. following migration file was generated.
public partial class PasswordDate : DbMigration
{
public override void Up()
{
AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime(nullable: false));
}
public override void Down()
{
AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime());
}
}
But when I run Update-Database command:
Update-Database -SourceMigration 201309020721215_PasswordDate
I get following error: Cannot insert the value NULL into column 'PasswordDate', table ''; column does not allow nulls. UPDATE fails.
The statement has been terminated.
Kindly suggest the solutions.
That's because you allowed NULL values in that column, then tried to make it non-nullable. It will subsequently try to migrate your existing data into that newly non-nullable column, which will break because you already have NULL values in there.
Two solutions:
1) Change it back to nullable
2) Give it a default value for items that don't have a value.
It's not possible to directly add a non-nullable column to a table that has historical data in the table if no default value is provided for that column.
What I do is
add the column as nullable.
provide an sql script to populate this newly added column.
alter the column to make is as non-nullable.
Code example(with postgres database):
public override void Up()
{
AddColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: true));
Sql(#"UPDATE ""public"".""YourTableName""
SET ""YourColumnName"" = Value you want to set
");
AlterColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: false));
}
Another way in EF core 6 would be to alter the migration script where the add column specifies a default value. You can then later drop this default value again.
public partial class AddOrderSource : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Add the column with a default value, then drop the default value.
// This creates a non-nullable column without the migration failing because of existing data.
migrationBuilder.AddColumn<int>(
name: "OrderSource",
table: "Orders",
type: "int",
nullable: false,
defaultValue: 1); // Sample default value
migrationBuilder.AlterColumn<int>(
name: "OrderSource",
table: "Orders",
oldDefaultValue: 1,
defaultValue: null
);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "OrderSource",
table: "Orders");
}
}

EF5 Code First - Changing A Column Type With Migrations

I am new to EF5 Code First and I'm tinkering with a proof-of-concept before embarking on a project at work.
I have initially created a model that looked something like
public class Person {
public int Id { get; set; }
public string FirstName { get; set;}
public string Surname {get;set;}
public string Location {get;set;}
}
And I added a few records using a little MVC application I stuck on the top.
Now I want to change the Location column to an enum, something like:
public class Person {
public int Id { get; set; }
public string FirstName { get; set;}
public string Surname {get;set;}
public Locations Location {get;set;}
}
public enum Locations {
London = 1,
Edinburgh = 2,
Cardiff = 3
}
When I add the new migration I get:
AlterColumn("dbo.People", "Location", c => c.Int(nullable: false));
but when I run update-database I get an error
Conversion failed when converting the nvarchar value 'London' to data type int.
Is there a way in the migration to truncate the table before it runs the alter statement?
I know I can open the database and manually do it, but is there a smarter way?
The smartest way is probably to not alter types. If you need to do this, I'd suggest you to do the following steps:
Add a new column with your new type
Use Sql() to take over the data from the original column using an update statement
Remove the old column
Rename the new column
This can all be done in the same migration, the correct SQL script will be created. You can skip step 2 if you want your data to be discarded. If you want to take it over, add the appropriate statement (can also contain a switch statement).
Unfortunately Code First Migrations do not provide easier ways to accomplish this.
Here is the example code:
AddColumn("dbo.People", "LocationTmp", c => c.Int(nullable: false));
Sql(#"
UPDATE dbp.People
SET LocationTmp =
CASE Location
WHEN 'London' THEN 1
WHEN 'Edinburgh' THEN 2
WHEN 'Cardiff' THEN 3
ELSE 0
END
");
DropColumn("dbo.People", "Location");
RenameColumn("dbo.People", "LocationTmp", "Location");
Based on #JustAnotherUserYouMayKnow's answer, but easier.
Try firstly execute Sql() command and then AlterColumn():
Sql(#"
UPDATE dbo.People
SET Location =
CASE Location
WHEN 'London' THEN 1
WHEN 'Edinburgh' THEN 2
WHEN 'Cardiff' THEN 3
ELSE 0
END
");
AlterColumn("dbo.People", "Location", c => c.Int(nullable: false));
I know this doesn't apply directly to the question but could be helpful to someone. In my problem, I accidentally made a year field a datetime and I was trying to figure out how to delete all the data and then switch the data type to an int.
When doing an add-migration, EF wanted to just update the column. I had to delete what they wanted to do and add my own code. I basically just dropped the column and added a new column. Here is what worked for me.
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TestingPeriodYear",
table: "ControlActivityIssue");
migrationBuilder.AddColumn<int>(
name: "TestingPeriodYear",
table: "ControlActivityIssue",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TestingPeriodYear",
table: "ControlActivityIssue");
migrationBuilder.AddColumn<DateTime>(
name: "TestingPeriodYear",
table: "ControlActivityIssue",
nullable: true);
}

Categories