0

I develop my ASP.NET MVC4 app using EF Code-first, also im using Migrations feature. I have specific entity and i want to set explicit id values for some reasons. How can i do this? I tried to mark id property with attribute like this:

public class NewsSource
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public string Title { get; set; }

    public string WebSiteUrl { get; set; }
}

Then i add corresponding migration, delete database and try to update database using Seed() method like this:

context.NewsSources.AddOrUpdate(x => x.Title,
            new NewsSource {Id = 654, Title = "ABC", WebSiteUrl = @"http://www.abc.com/"},
            new NewsSource {Id = 22, Title = "XYZ", WebSiteUrl = @"http://XYZ.ru/"});

And ive got this error: "Cannot insert explicit value for identity column in table 'NewsSources' when IDENTITY_INSERT is set to OFF". How can i set identity_insert to ON using EF and migrations. As i understood from many topics its impossible and i have to use direct SQL-commands. Am i wrong?

ifeelgood
  • 165
  • 2
  • 8
  • I think you're not wrong. As long you're putting the `[Key]` annotation, EF will want to handle that ID by it-self. Maybe you should consider another structure for your table. I may have wrong, but my research gave me the same result as yours : it's not possible. – Atlasmaybe Aug 22 '13 at 07:30

2 Answers2

1

I had a problem when I tried to change a column to an IDENTITY field when it was originally not an identity field. See this question and this one. You have to remove the column and recreate it to remove IDENTITY so fixing up foreign keys etc is probably a step too far for Entity Framework to do in a migration. You will have to alter the Up() and Down() methods yourself, or you may get away with doing it in the database.

Community
  • 1
  • 1
Colin
  • 22,328
  • 17
  • 103
  • 197
  • I just got bitten by this as well... DropColumn("Customer", "CustomerId"); AddColumn("Customer", "CustomerId", c => c.Long(nullable: false, identity: false)); solved it! – Peter Gfader Mar 29 '16 at 12:48
0

What happens if you remove the DatabaseGenerated attribute and just leave the [Key] attribute?

public class NewsSource
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string WebSiteUrl { get; set; }
}

I ran into this issue awhile back and I believe this was a work around for me. I can't test it now since I don't have any projects in front of me with EF in them. All I can say is EF code first and the nuget migrations package is a great thing, if you treat it the way you are supposed to treat it. I have gotten myself into a number of WTF moments when using the two together and trying to seed complex related models. Good luck!

ledgeJumper
  • 3,560
  • 14
  • 45
  • 92