0

I have existing model with table in SQL server, also with data. I created with EF Core new model - some bools, ForgeinId, Id with attribute - [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Next i added migration, i had to add custom SQL beacuse i have to add new rows and connect it to previous table.

First model(allready existing in db):

public Guid Id {get; set;}
public virtual Table Table {get; set;} // that is just added so this is included in migration
// some data

Second model(just created):

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid tableId {get; set;}
public Guid ForgeinId {get; set;}
public ForgeinTable ForgeinTable {get; set;}
// some data

Migration:

migrationBuilder.CreateTable(
name: "Table",
columns: table => new
{
tableId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
//some data
}
migrationBuilder.Sql("insert into *newTableName* (ForgeinId) select Id from *oldTableName*;");

// adding index

Next i got error about insert NULL in tableId column in my new table. So why identity dont work?

Answer is pretty simple - i have to add

defaultValueSql: "newsequentialid() 

to my Id, next delete this attribute from my SQL table. More info here: Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls.

JJJ
  • 51
  • 5

1 Answers1

0

You can try to add migrattion without any custom sql and check if newTableName has identity on id column. If it is - try to use migrationBuilder.Sql(...) just on end of your protected override void Up(MigrationBuilder migrationBuilder) method in migration.

IgorM
  • 31
  • 7
  • Same problem, i added it after CreateIndex. Now i just read that EF atributes - [DatabaseGenerated(DatabaseGeneratedOption.Identity)], work only on .add() update() methods, then they add new id. Is there any way to set identity atribute in SQL table? – JJJ Mar 01 '18 at 17:01
  • Maybe you can add `DEFAULT newid()` for Id on newTable? Any way you can find answer on: https://stackoverflow.com/questions/23081096/entity-framework-6-guid-as-primary-key-cannot-insert-the-value-null-into-column – IgorM Mar 01 '18 at 17:18
  • Okay, that works for me - defaultValueSql: "newsequentialid()", next just delete this attribute from SQL, and thats work. – JJJ Mar 02 '18 at 06:01