Entity Framework Code First Migrations: Set Primary Key Value

后端 未结 3 2143
感情败类
感情败类 2020-12-05 23:59

I have a table that stores some extra data for some rows of a table like:

public class QuoteExtra
{
    [Key]
    public int QuoteId { get; set; }
    // Mor         


        
相关标签:
3条回答
  • 2020-12-06 00:35

    It is right solution but only for a new table. If you change database generated option for an existing table, EF migrations are not able to perform this change and your QuoteId column is still marked as Identity in the database.

    0 讨论(0)
  • 2020-12-06 00:45

    I could'nt solve this Problem with your Hints then i've tried to re-create the whole Database but it wasnt working, too.

    To fix this you have to remove the identity: true property on the first(!) creation of the Column (e.g. Initial-Migration).

    Maybe it will help someone..

    0 讨论(0)
  • 2020-12-06 00:52

    This is the proper way of creating a PK without Identity Autoincrement enabled:

    public class QuoteExtra
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int QuoteId { get; set; }
        // More fields here
    }
    

    However, if you add DatabaseGenerated(DatabaseGeneratedOption.None)] after EF Migrations has already created the table, it quietly does nothing to the table. If this is your scenario you need to add a manual migration to drop the table:

    add-migration RecreateQuoteExtra
    

    And in the migration:

    public override void Up()
    {
        DropTable("QuoteExtra");
    }
    

    EF Automatic Migrations will then automatically recreate the table without the Identity constraint, which will then allow you to set the PK value anytime, without having to run any special commands like IDENTITY_INSERT ON.

    It sounds like a less destructive way to do this is coming in EF7 ("Data Motion"), or you could write a lot of manual sql yourself in the migration to create temp tables and move data around if you wanted to avoid losing existing data in the table.

    EDIT: Depending on your scenario EF Migrations might not recreate the table - if the class already exists and is already added to your DbContext it will just drop it and leave it at that, meaning your manual migration has to not only drop but also create the table. Not a big deal since the scaffolded code EF Migrations generates for you from add-migration will create these statements for you, but it is a bit more code to check over for issues.

    0 讨论(0)
提交回复
热议问题