我试图找出如何首先通过Entity Framework代码向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; }
}
第二个通过流利的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列的类型为timestamp,其可空属性为false。这是EF Core的限制还是我试图做错了?
答案 0 :(得分:0)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>()
.Property(b => b.MyVersionProperty)
.IsRowVersion();
}