【发布时间】:2016-07-01 13:53:23
【问题描述】:
我正在使用 EF 代码优先方法,想将 Id 字段更改为 guid,但似乎无法通过以下错误。
这是我的第一次迁移:
public partial class CreateDownloadToken : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.DownloadTokens",
c => new
{
Id = c.Int(nullable: false, identity: true),
FileId = c.Int(),
UserId = c.String(nullable: false, maxLength: 128),
ValidUntil = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Files", t => t.FileId)
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true)
.Index(t => t.FileId)
.Index(t => t.UserId);
}
public override void Down()
{
DropForeignKey("dbo.DownloadTokens", "UserId", "dbo.Users");
DropForeignKey("dbo.DownloadTokens", "FileId", "dbo.Files");
DropIndex("dbo.DownloadTokens", new[] { "UserId" });
DropIndex("dbo.DownloadTokens", new[] { "FileId" });
DropTable("dbo.DownloadTokens");
}
}
后来我意识到我需要 Id 列作为 GUID,所以我更改了我的模型文件:
public class DownloadToken
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Guid Id { get; set; }
public int? FileId { get; set; }
[ForeignKey("FileId")]
public virtual File File { get; set; }
[Required]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
[Required]
public DateTime ValidUntil { get; set; }
}
当运行Add-Migration ChangeDownloadTokenIdToGuid 时,它会生成这个文件:
public partial class ChangeDownloadTokenIdToGuid : DbMigration
{
public override void Up()
{
DropPrimaryKey("dbo.DownloadTokens");
AlterColumn("dbo.DownloadTokens", "Id", c => c.Guid(nullable: false));
AddPrimaryKey("dbo.DownloadTokens", "Id");
}
public override void Down()
{
DropPrimaryKey("dbo.DownloadTokens");
AlterColumn("dbo.DownloadTokens", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.DownloadTokens", "Id");
}
}
使用Update-Database 运行此文件会导致此错误:
Identity column 'Id' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.
任何想法为什么会发生这种情况?
【问题讨论】:
标签: c# asp.net entity-framework entity-framework-migrations