0

I am a bit mystified by some Entity Framework behavior. I have a class like this:

 Account
 -ID (PK, int, not null)
 -AccountID (PK, int, not null)
 -ClientID
 -... other scalars

The AccountID field should come from an API we consume. Unfortunately, I did not know at the time that Entity Framework does not support non-db generated primary keys. So I have to drop the AccountID as part of the primary key.

When I remove the [Key] attribute from the AccountID field, I get some odd behavior from the migration. Here are the lines from the migration which make no sense to me.

DropColumn("dbo.Account", "ClientID");
RenameColumn(table: "dbo.Account", name: "ID", newName: "ClientID");
.... more stuff
AlterColumn("dbo.Account", "ID", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.Account", "ID");

Why would Entity Framework be trying to drop this unrelated column (ClientID)? And why is it trying to use a column in the AlterColumn statement which no longer exists (ID has been renamed to ClientID)?

Stephen Panzer
  • 289
  • 5
  • 16

1 Answers1

0

You can use a non-db generated primary key.

If you are doing code first you can use the attribute:

[DatabaseGenerated(DatabaseGenerationOption.None)]
public int (or string or w/e) Id { get; set; }

Are you trying to use code first or database first or how are you trying to create the model? I can edit my answer with more details if you need.

John
  • 6,503
  • 3
  • 37
  • 58
  • I'm using Code First. I'm not sure why I haven't tried DatabaseGeneratedOption.None, however why I try to mark the ID column with DatabaseGeneratedOption.Identity and the AccountID column with DatabaseGeneratedOption.None, I get this error, which I created a new question for: http://stackoverflow.com/questions/26538013/debugging-a-dependent-property-in-a-referentialconstraint-is-mapped-to-a-store. – Stephen Panzer Oct 23 '14 at 21:51