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.