c# - 如何使用 Entity Framework `ValueComparer<T>` ?

标签 c# asp.net .net entity-framework entity-framework-core

我正在处理一个 ASP.NET 3.1 项目。 类(class)EmployeeSummary包含公共(public)属性(property) string[] Roles

public string[] Roles { get; set; }

并为字符串数组设置了值转换器:

          modelBuilder.Entity<EmployeeSummary>()
                .Property(e => e.Roles)
                .HasConversion(v => string.Join(",", v),
                    v => v.Split(new[]
                        {
                            ","
                        }, StringSplitOptions.RemoveEmptyEntries)
                        .ToList()
                        .Distinct(StringComparer.OrdinalIgnoreCase)
                        .ToArray());

我得到以下 System.InvalidOperationException表示我没有设置值比较器:

The property 'Roles' on entity type 'EmployeeSummary' is a collection or enumeration type 
with a value converter but with no value comparer. 
Set a value comparer to ensure the collection/enumeration elements are compared correctly.

我的方法是添加(类似于 Microsoft documentation 中的示例)

  • A var valueComparer在类里面EmployeeSummary
  • 设置为 new ValueComparer<string[]>而不是 new ValueComparer<List<int>>
  • 检查两个数组是否相同。 然而,这不起作用:
        public string[] Roles { get; set; }

        private var valueComparer = new ValueComparer<string[]>(
             (c1, c2) => c1.SequenceEqual(c2));

带有无法解析构造函数的消息。这是正确的方法吗,或者我该如何解决此错误消息?

最佳答案

您需要在方法HasConversion 中设置ValueComparer

一个可行的例子是:

            modelBuilder.Entity<EmployeeSummary>()
            .Property(e => e.Roles)
            .HasConversion(
                v => string.Join(',', v),
                v => v.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList()
                    .Distinct(StringComparer.OrdinalIgnoreCase)
                    .ToArray(), new ValueComparer<ICollection<string>>(
                    (c1, c2) => c1.SequenceEqual(c2),
                    c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
                    c => c.ToList()));

关于c# - 如何使用 Entity Framework `ValueComparer<T>` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64595477/

相关文章:

c# - 是否可以限制 EventWaitHandle 的设置/重置?

c# - 尽管已声明 !IsPostBack 已声明,但分数整数卡住了

.net - 进程被终止后,DLL 仍处于锁定状态

c# - 标签目标接收值意味着什么?

c# - NET公共(public)语言运行时的泛型实现是什么

c# - Azure 认知服务 TTS - 示例应用程序中其他语言的错误

c# - SQL查询在转换日期后更改列名

c# - 使用 C# 在复选框列表中选择单个项目

javascript - 如何禁用打印屏幕?

c# - 尝试使用 Entity Framework 从数据库下载大文件时出错