简体   繁体   English

Entity Framework Core RowVersion列未使用PostgreSQL进行更新

[英]Entity Framework Core RowVersion column not updating using PostgreSQL

I've set a RowVersion column for my entity but it seems that it isn't storing anything on creates or updates. 我为我的实体设置了一个RowVersion列,但它似乎没有在创建或更新中存储任何内容。

it have this configuration in the DbContext OnModelCreating : 它在DbContext OnModelCreating有这个配置:

 modelBuilder.Entity<Author>()
    .Property(a => a.RowVersion)
    .IsConcurrencyToken()
    .ValueGeneratedOnAddOrUpdate();

However, the RowVersion column is always NULL, even after an entity update / create. 但是,即使在实体更新/创建之后,RowVersion列也始终为NULL。

By the way, I'm using PostgreSQL with the Npgsql Library (NuGet). 顺便说一下,我正在使用PostgreSQL和Npgsql库(NuGet)。 In the docs, it says that PostgreSQL doesn't support computed values on add or update 在文档中,它表示PostgreSQL在添加或更新时不支持计算值

Is it the reason why it doesn't work? 这是它不起作用的原因吗?

If so, why could we circumvent this limitation? 如果是这样,为什么我们可以绕过这个限制呢?

Also, I've tested with: 另外,我测试过:

modelBuilder.Entity<Author>().Property<byte[]>("RowVersion")
    .HasColumnName(ShadowPropertiesDb.RowVersion)
    .IsRowVersion();

It results in the same problem. 它导致了同样的问题。

In PostgreSQL RowVersion is predefined as a column named "xmin". 在PostgreSQL中,RowVersion被预定义为名为“xmin”的列。

Example property (only for Npgsql): 示例属性(仅适用于Npgsql):

[ConcurrencyCheck]
[Column("xmin",TypeName = "xid")]
public long RowVersion { get; set; }

If you want the property to be byte[] type: 如果您希望属性为byte []类型:

Step 1: Change property type to byte[] 第1步:将属性类型更改为byte []

[ConcurrencyCheck]
[Column("xmin",TypeName = "xid")]
public byte[] RowVersion { get; set; }

Step 2: Add converter in "OnModelCreating(ModelBuilder builder)" 第2步:在“OnModelCreating(ModelBuilder构建器)”中添加转换器

var converter = new ValueConverter<byte[], long>(
     v => BitConverter.ToInt64(v, 0), 
     v => BitConverter.GetBytes(v));

builder.Entity<Author>()
   .Property(_ => _.RowVersion)
   .HasConversion(converter);

================ For many database type ================= ================对于许多数据库类型=================

Property: 属性:

[ConcurrencyCheck]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public byte[] RowVersion { get; set; }

In "OnModelCreating(ModelBuilder builder)": 在“OnModelCreating(ModelBuilder构建器)”中:

if (Database.IsNpgsql())
{
    var converter = new ValueConverter<byte[], long>(
        v => BitConverter.ToInt64(v, 0),
        v => BitConverter.GetBytes(v));

    builder.Entity<Author>()
            .Property(_ => _.RowVersion)
            .HasColumnName("xmin")
            .HasColumnType("xid")
            .HasConversion(converter);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM