5

I have looked at this post and tried to do it this way

Autogenerate primary key (Guid) Entity Framework CTP5

 [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public Guid CompanyID { set; get; }

However I am still getting the error

Identity column 'CompanyID' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.

This is when I run Update-Database command on the package manager console.

Community
  • 1
  • 1
Johnathon64
  • 1,280
  • 1
  • 20
  • 45
  • I have a feeling that it's because I have data already in the CompanyID column whcih is why it's not letting me – Johnathon64 Jul 29 '15 at 14:10
  • Are you adding the [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] as part of the migration? The answer by lightyeare here http://stackoverflow.com/questions/23081096/entity-framework-6-guid-as-primary-key maybe of some help. – Eric Yeoman Jul 29 '15 at 15:41
  • Just tried that and it didn't work I did this: AlterColumn("dbo.dbCompanies", "CompanyID", c => c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()")); – Johnathon64 Jul 29 '15 at 15:58
  • Are your existing CompanyId's already Guid's? Just wondering as in one of your previous questions a CompanyId was an int. (http://stackoverflow.com/questions/30244351/adding-entity-to-identity-model) – Eric Yeoman Jul 29 '15 at 17:12
  • no they are not, so should I delete all entries and basically change it to guid? – Johnathon64 Jul 29 '15 at 17:35
  • 1
    Yeah, if you want to use Guid's then you'll need to change the current entries to use those as well, you can't mix datatypes :) Have you checked for any foreign key constraints, or any existing code which is expecting an int? (Not sure where you are in the application lifecycle) – Eric Yeoman Jul 29 '15 at 21:59
  • There are 3 tables that depend on that primary key, so I will probably have to delete those as well. I'll give this a try today and let you know how it goes! – Johnathon64 Jul 30 '15 at 07:27

1 Answers1

3

Had the same issue, the only thing helped me is dropping database to initial empty state, removing all migrations and creating a new one with proper GUID key:

  1. Update-Database -TargetMigration:0
  2. Remove all migrations
  3. Add-Migration InitialCreate
  4. Update-Database

I agree that this is not a best solution, but it was acceptable for me since I had started project a few hours before.

Vsevolod Krasnov
  • 1,482
  • 2
  • 13
  • 20