Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autogenerate GUID column that is not a primary key in Entity Framework

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?

like image 671
Stephen Panzer Avatar asked Oct 21 '22 00:10

Stephen Panzer


1 Answers

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.

like image 173
ESG Avatar answered Oct 24 '22 11:10

ESG