EF code first migrations, DB generated guid keys

2019-07-29 16:58发布

问题:

The question as a one liner

How do I get EF to generate as part of a code first migration

ALTER TABLE [DMS].[Forms] ADD  CONSTRAINT [DF_DMS.Forms_Id]  DEFAULT (newid()) FOR [Id]
GO

More detail of the problem

I'm to build out a simple table to store information about forms, as it happens I already have this working for another table in my db but if I show you the code (see below) you'll realise the issue i'm hitting is more strange than it might seem ...

First the working example entity:

[Table("Files", Schema = "DMS")]
public class File
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    ...
}

ok now the not working one ...

[Table("Forms", Schema = "CMS")]
public class Form
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    ...
}

As stated in the question, i'm using EF code first, so here's the migration code:

The working one:

CreateTable(
    "DMS.Files",
    c => new
        {
            Id = c.Guid(nullable: false),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

... and the non working one ...

CreateTable(
    "CMS.Forms",
    c => new
        {
            Id = c.Guid(nullable: false),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

So all is good ... then I migrate my db with an "update-database" command and script the two tables ...

The working one:

...
CREATE TABLE [DMS].[Files](
    [Id] [uniqueidentifier] NOT NULL,
    ...
 CONSTRAINT [PK_DMS.Files] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [DMS].[Files] ADD  CONSTRAINT [DF_DMS.Files_Id]  DEFAULT (newid()) FOR [Id]
GO
...

... and the non working one ...

...
CREATE TABLE [CMS].[Forms](
    [Id] [uniqueidentifier] NOT NULL,
    ...
 CONSTRAINT [PK_CMS.Forms] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
...

回答1:

I have no idea why but this works and fixes the problem ...

The working one (no changes):

CreateTable(
    "DMS.Files",
    c => new
        {
            Id = c.Guid(nullable: false),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

... and the non working one (with fix applied)...

CreateTable(
    "CMS.Forms",
    c => new
        {
            Id = c.Guid(nullable: false, defaultValueSql: "newid()"),
            ...
        })
    .PrimaryKey(t => t.Id)
    ...;

I figure I must have come across some sort of bug in EF that results in it generating the migration correctly in some cases.