44

我知道这不是最理想的解决方案,但我需要向我的一个 EF Code First 对象添加一个自动递增字段。此列 id 不是 Id,它是一个 guid。

无论如何我可以在代码中定义自动递增字段,还是自己创建列并在数据库中定义它的自动递增工作?

4

3 回答 3

70

您可以使用 注释该属性DatabaseGenerated(DatabaseGeneratedOption.Identity)。EF 只允许每个表有一个标识列。

public class Foo
{
    [Key]
    public Guid Id { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Bar { get; set; }
}
于 2012-05-03T08:36:30.930 回答
7

旧帖子认为我会分享我在 Entity Framework 6.1.3 中发现的内容。

我使用 C# 和 .NET Framework 4.6.1 创建了一个简单的数据层库,添加了一个简单的存储库/服务类、一个代码优先上下文类,并将我的 web.config 文件指向本地 SQL Express 2014 数据库。

在实体类中,我将以下属性构造函数添加到 Id 列:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

然后我通过在 Visual Studio 2015 包管理器中键入以下内容创建了一个新迁移:

添加迁移

为迁移命名,然后等待创建 DbMigtation 类。编辑类并添加以下 CreateTable 操作:

CreateTable(
"dbo.Article",
    c => new
    {
        Id = c.Guid(nullable: false, identity: true),
        Title = c.String(),
        Content = c.String(),
        PublishedDate = c.DateTime(nullable: false),
        Author = c.String(),
        CreateDate = c.DateTime(nullable: false),
    })
    .PrimaryKey(t => t.Id);
}

上表是一个示例,这里的关键点是以下构建器注释:

nullable: false, identity: true

这告诉 EF 将该列指定为 not nullabe,并且您希望将其设置为由 EF 播种的标识列。

使用以下命令再次运行迁移:

update-database

这将运行迁移类首先删除表(Down() 方法)然后创建表(Up() 方法)。

Run your unit tests and/or connect to the database and run a select query you should see your table in its new form, add some data excluding the Id column and you should see new Guid's (or whatever data type your choose) to be generated.

于 2016-04-30T22:00:02.040 回答
0

For those stumbling onto this question for EF Core, you can now create an auto-incrementing column with your model builder as follows:

builder.Entity<YourEntity>().Property(e => e.YourAutoIncrementProperty).UseNpgsqlIdentityAlwaysColumn();

Reference: https://www.npgsql.org/efcore/modeling/generated-properties.html

于 2020-02-26T15:58:36.027 回答