1

我试图弄清楚我应该如何首先通过实体框架代码向 SQL Server 中的数据表添加Timestamp/rowversion列。

这是使用 EF Core V2.0。

我尝试了两种方法来实现这一点,第一种:

public class Contact
{
    public int ContactId { get; set; }
    public string ContactName { get; set; }
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

第二个通过 fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        modelBuilder.Entity(entityType.Name).Property<DateTime>("Inserted");
        modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModified");
        modelBuilder.Entity(entityType.Name).Property<byte[]>  ("RowVersion");
    }
}

在我运行后的两种情况下Add-Migration,我都会得到以下信息:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Contacts",
        columns: table => new
        {
            ContactId    = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            CompanyName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            ContactName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            FirstName    = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            Inserted     = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastModified = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastName     = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            RowVersion   = table.Column<byte[]>  (type: "varbinary(max)", nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Contacts", x => x.ContactId);
        }
    );
}

我本来希望该RowVersion列是 typetimestamp并且它的nullable属性是false. 这是 EF Core 的限制还是我试图不正确地执行此操作?

4

1 回答 1

0
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<MyEntity>()
      .Property(b => b.MyVersionProperty)
      .IsRowVersion();
}
于 2017-12-07T20:14:45.373 回答