我正在使用代码优先方法为现有数据库生成迁移。 C#中的我(简化)实体看起来像这样
public class User
{
public Guid Id { get; set; }
public Guid Subject { get; set; }
public string Name { get; set; }
}
然后配置就像这样
HasKey(c => c.Id)
.Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(c => c.Subject)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute {IsUnique = true}));
Property(c => c.Name).HasMaxLength(50).IsRequired();
Subject属性已经以类似的方式更新,并且它可以正常工作。从EF生成的SQL脚本就像这样(也简化为迁移包含DB模型中的更多更改。它缺少MigrationHistory Insert语句,我已将其排除,因为它太大了。):
IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_Subject' AND object_id = object_id(N'[dbo].[User]', N'U'))
DROP INDEX [IX_Subject] ON [dbo].[User]
EXECUTE sp_rename @objname = N'dbo.User.Subject', @newname = N'Subject_Old', @objtype = N'COLUMN'
ALTER TABLE [dbo].[User] ADD [Subject] [uniqueidentifier] NOT NULL DEFAULT newsequentialid()
CREATE UNIQUE INDEX [IX_Subject] ON [dbo].[User]([Subject])
DECLARE @var91 nvarchar(128)
SELECT @var91 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.User')
AND col_name(parent_object_id, parent_column_id) = 'Subject_Old';
IF @var91 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[User] DROP CONSTRAINT [' + @var91 + ']')
ALTER TABLE [dbo].[User] DROP COLUMN [Subject_Old]
所以我将DatabaseGeneratedOption。无更改为身份。
HasKey(c => c.Id)
.Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
并生成迁移:
public override void Up()
{
DropPrimaryKey("dbo.User");
AlterColumn("dbo.User", "Id", c => c.Guid(nullable: false, identity: true));
AddPrimaryKey("dbo.User", "Id");
}
public override void Down()
{
DropPrimaryKey("dbo.User");
AlterColumn("dbo.User", "Id", c => c.Guid(nullable: false));
AddPrimaryKey("dbo.User", "Id");
}
但是当更新数据库时,我没有得到默认值的约束,因为我已经使用了Subject的属性,似乎生成的SQL脚本中缺少 DEFAULT newsequentialid()。这是脚本(也不包括INSERT语句):
ALTER TABLE [dbo].[User] DROP CONSTRAINT [PK_dbo.User]
DECLARE @var0 nvarchar(128)
SELECT @var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.User')
AND col_name(parent_object_id, parent_column_id) = 'Id';
IF @var0 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[User] DROP CONSTRAINT [' + @var0 + ']')
ALTER TABLE [dbo].[User] ALTER COLUMN [Id] [uniqueidentifier] NOT NULL
ALTER TABLE [dbo].[User] ADD CONSTRAINT [PK_dbo.User] PRIMARY KEY ([Id])
用户ID不会作为FK在任何地方引用。 我有EntityFramework 6和MSSQL server express 14。 我试过使用属性注释,但结果是一样的。 我的问题是:我做错了什么或者这是一个EntityFramework的错误?