I'm moving to Entity Framework from an existing model and database. In that database, there are several tables with GUID columns which are not primary keys (or keys at all!). Each table has an ID column. The GUID columns have the ROWGUIDCOL property defined on them, as well as a DEFAULT(newid()).
Now, when I insert into the DB, I get all zeroes for this column.
I've tried using data annotations:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Guid {get; set;}
The problem with this is that it drops the identity property on my ID column (and gives me insert errors). Beyond that, I noticed that for the following migration, EF actually generates identical SQL for both the up and down methods:
public override void Up()
{
AlterColumn("dbo.Client", "Guid", c => c.Guid(nullable: false, identity: true));
}
public override void Down()
{
AlterColumn("dbo.Client", "Guid", c => c.Guid(nullable: false));
}
With the generated sql of:
ALTER TABLE [dbo].[Client] ALTER COLUMN [Guid] [uniqueidentifier] NOT NULL
Why does the above migration create the same sql for both statements? How do I get EF to generate GUIDs? Can I/must I do this in client (code) space? If I must, how could I guarantee uniqueness across tables?
DatabaseGenerationOption.Identity should be used for identity column.
Try using DatabaseGenerationOption.Computed instead. It should prevent EF from sending a value when inserting the column, and it should pull the db generated value properly on SaveChanges.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With