使用Guid编码第一个EF并发令牌

我试图使用Guid作为并发令牌,但是每次尝试插入记录时,都会出现一个关于无法添加空值的异常。

生成的SQL和异常消息:

Failed executing DbCommand (4ms) [Parameters=[@p0='?' (DbType = Guid),@p1='?' (Size = 10) (DbType = AnsiString),@p2='?' (Size = 150) (DbType = AnsiString)],CommandType='Text',CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [Application] ([Id],[Code],[Name])
VALUES (@p0,@p1,@p2);
SELECT [Version]
FROM [Application]
WHERE @@ROWCOUNT = 1 AND [Id] = @p0; System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Version',table 'MyCompany.dbo.Application'; column does not allow nulls. INSERT fails.
public class Application
    {
        public Guid Id { get; set; }

        public string Name { get; set; }

        public string Code { get; set; }

        // A concurrency token for use with the optimistic concurrency checking
        public Guid Version { get; set; }
    }

使用模型构建器:

builder.Property(c => c.Version)
                .IsConcurrencyToken()
                .ValueGeneratedOnAddOrupdate();

基本上,我需要有关我做错事情的建议。

guojinfei 回答:使用Guid编码第一个EF并发令牌

我看到的一些东西需要纠正。

modelbuilder语句应作如下修改

 modelBuilder.Entity<Application>().Property(app => app.Version).ValueGeneratedOnAddOrUpdate().IsConcurrencyToken();

请记住,在Version属性上没有指定任何价值生成策略。当我们以这种状态生成迁移时,生成的Migration.cs文件在new Guid("00000000-0000-0000-0000-000000000000"));方法内部分配一个defaultValue Up()。下面是一个示例

Contact Entity

Migration without Required attribute and without any value generation strategy

另一方面,如果您希望每次在表中插入新行时都添加新的Guid,则应使用计算字段。下面的两个图像显示了用属性装饰的Version属性的结构以及生成的Migration。另外,需要添加以下行代码来标记计算。

modelBuilder.Entity<Contact>().Property(t => t.Version).HasComputedColumnSql("NEWID()");

Migration with Computed Field

Updated Entity With Computed Field

有了上述更改,您将为插入的每一行成功生成一个新的Guid

本文链接:https://www.f2er.com/3159883.html

大家都在问