Trying to alter a column from a text field to a jsonb field using Entity Framework code-first migrations.
The column mostly has json objects stored as text but some are not valid json. When trying to run the migration it throws the error:
Exception: 42804: column "Message" cannot be cast automatically to type jsonb
Code:
migrationBuilder.AlterColumn<string>(
name: "Message",
schema: "database",
table: "ScheduledEvent",
type: "jsonb",
nullable: false,
oldClrType: typeof(string),
oldType: "text");
In this thread, https://github.com/npgsql/efcore.pg/issues/144, they have the same issue and say the solution was to add a USING clause.
How can I update the code first EF model to add a USING clause in the migration?
Related
I use mySQL database for my project and want to create index on column.
I'm using codefirst approach
Here is my migration
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RecruitmentAgencies_AbpTenants_TenantId",
table: "RecruitmentAgencies");
migrationBuilder.DropIndex(
name: "IX_RecruitmentAgencies_TenantId",
table: "RecruitmentAgencies");
migrationBuilder.AddColumn<string>(
name: "ContactEmail",
table: "RecruitmentAgencies",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_RecruitmentAgencies_ContactEmail",
table: "RecruitmentAgencies",
column: "ContactEmail");
}
and when I try to apply it, I get this error
BLOB/TEXT column 'ContactEmail' used in key specification without a key length
How I can fix this?
The issue is related that MySQL can index only the first N chars of a BLOB or TEXT column.
To solve this issue, try to remove the TEXT or BLOB column from the index or unique constraint or set another field as primary key. Besides, you could also try to use VARCHAR type and place a limit of length on it (or try to set the string MaxLength annotations).
Reference: MySQL error: key specification without a key length
I am working in a company where a project has been brought in house because the external team tasks with building the system have not done a great job and thus been fired.
An issue that I have is that we have an existing database, where some tables where seed data should have been done through a migrationBuilder looks to have just been inserted via SSMS \ SQL Server Insert scripts.
as a result I get an error like this when adding seeding scripts so that when we spin up an new isntance of the database this works, but on an existing environment such as dev, test and staging it does not.
Violation of PRIMARY KEY constraint 'PK_xxxx'. Cannot insert duplicate key in object 'forms.AnswerTypes'. The duplicate key value is (1)
The only potential way I have found around this is from this link here
https://entityframeworkcore.com/knowledge-base/54553668/add-or-update-data-to-existing-database-with-entity-framework
But hope that there are better ways that this can be acheived as I cannot delete the data as part of the migration because its already used and being referenced by other tables so the ripple effect is wide ranging.
An example of the sort of data that I am trying to seed is like this;
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
schema: "forms",
table: "Rules",
columns: new[] { "RuleId", "Rules" },
values: new object[] { 1, "Any" });
migrationBuilder.InsertData(
schema: "forms",
table: "Rules",
columns: new[] { "RuleId", "Rules" },
values: new object[] { 2, "All" });
}
So, the question is, is it possible with migrationBuilder to check is data exists prior to inserting?
You can write custom SQL and stuff and add it to your migration script;
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/operations
There's also .Sql():
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli#customize-migration-code
migrationBuilder.Sql(
#"
UPDATE Customer
SET Name = FirstName + ' ' + LastName;
");
Which you could use. My team and i use EF6 still but we use the same principle. Our migrationscript sometimes have additional SQL statements to move any data around or generate default data when adding a column etc.
I have two table A and B
Table A - Id Primary key not identity
Table B - Id Primary key not identity - Id Primary key not identity
How to create A and B Table primary key columns without identity(1,1) in entity framework 6 and apply sequence for these two table.
and this two tables need to implement sequence in SQL
if example Table A insert one record id is 1. and i will insert the Table B id is 2 like this
I was checked Identity off not working in script and Entity framework 6
and also not able to create sequence In entity framework 6
But EFCore has sequencial feature
modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared")
.StartsAt(1000)
.IncrementsBy(5);
modelBuilder.Entity<A>()
.Property(o => o.Id)
.HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers");
In this
HasSequence not available in Entity Framework 6
how to create sequence in EF 6 code first
Any one know please share
Add the Sequence in query in last Migration using following procedure
public override void Up()
{
Sql("CREATE SEQUENCE tbl_seq START WITH 1 INCREMENT BY 1;");
..........
..........
CreateTable(
"dbo.Table_A",
c => new
{
id = c.Long(nullable: false, identity: false, defaultValueSql:
"NEXT VALUE FOR tbl_seq"),....
}
CreateTable(
"dbo.Table_B",
c => new
{
id = c.Long(nullable: false, identity: false, defaultValueSql:
"NEXT VALUE FOR tbl_seq"),....
}
Set in this place change the migration for create table of those tables set
identity: false,
defaultValueSql: "NEXT VALUE FOR tbl_seq"
after update the database. we check those table applied the sequence on those tables.
This is short: I have mistakenly set a property string when it should've been int. There are no constraints as this int may be optional. Even though I could make the int nullable, I rather have it a default value of zero.
Then when I try to run migrations:
Cannot insert the value NULL into column 'Edad', table
'EduPlaTools.dbo.Profesor'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
Which makes sense. What it's doing is updating the fields, and since many fields had "NULL", it's getting inserted. Is there a way to map those NULLs into zeroes automatically? Or do I need to do an SQL Statement?
Here's the migrationBuilder code:
migrationBuilder.AlterColumn<int>(
name: "Edad",
table: "Profesor",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
If you are trying to change the type of a column and there are already existing records in your table, those records need to have some value specified for each of the new columns. If you have not specified a default value for the column, the database will attempt to use NULL, which will fail because the column does not allow nulls.
Oh no. I need to apologize. So dumb for not realizing this, Entity Framework apparently scaffolded other table with a similar property Profesor, when in fact it was Estudiante that needed change.
migrationBuilder.AlterColumn<int>(
name: "Edad",
table: "Estudiante",
nullable: false,
oldClrType: typeof(string),
oldNullable: true,
defaultValue: 0);
Now everything is working! Thanks everybody!
Entity Framework 6 with a Database Generated field is failing on insert. From what I've read once you mark a column as DatabaseGenerated, EF won't try to insert/update anything into that field, which is especially important in my case because the fields on the database are SQL Server computed columns and not just default values, which is what I've seen in a lot of similar questions on Stack Overflow/Google.
Column definition (using a User Defined Function in the computed column):
ALTER TABLE dbo.MyModel ADD [TotalUnits] AS ([dbo].[CalculateTotalUnits]([Id]));
EF definition:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public decimal TotalUnits { get; private set; }
And then I'm just doing a
var myNewModel = new MyModel();
DbContext.MyModels.Add(myNewModel);
DbContext.SaveChanges();
Which gives:
System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'TotalUnits', table 'MyDatabase.dbo.MyModel'; column does not allow nulls. INSERT fails.
Why is EF trying to insert a NULL value into a computed column, and how can I tell it not to?
Turns out when running integration tests EF was configured to use Automatic Migrations instead of our own migrations. Since the computed columns were being added in a custom SQL script during the Up method of a migration, the columns weren't actually computed columns during the tests but were in fact generated by EF as regular decimal (non-nullable) fields. Thus trying to add a new model to the context was causing EF to insert NULL into those columns and blowing up.
Solution is to actually run the migrations in the integration tests. Once the column is actually computed than EF stops tracking it.