EF Core 3 嵌套值转换无法翻译

时间:2021-01-04 22:13:22

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

更新

问题的症结在于在 where 子句中的属性上使用了嵌套字段;我提供了一个简化的示例(失败并出现相同的“无法翻译”错误)作为说明。如需更完整的图片,请阅读原始标题下的内容。

以下子句(在我开始使用此嵌套属性之前,查询的其余部分正在工作)

where (r.Status.IntVal == (int)StatusEnum.Answered) // IntVal is just an int

在运行时被翻译成

.Where(ti => ti.Outer.Status.IntVal == 1) // right hand side translates as expected

所以问题是:您如何编写适当的 ValueConverter(或您采取的其他步骤)以便在 EntityFramework 中正确读取和评估这样的嵌套字段?

原帖

我最近将我的一个 EF 模型(使用 EF Core v3.1.3)上的字段从 enum 更新为具有 System.Enum 字段的类。因为我希望数据库 / EF 将该字段视为基础整数值(就像它对 enum 所做的那样),所以我在 fluent API 中使用了 .HasConversion(),但我得到了可怕的“可能无法翻译”错误。 以下行是导致问题的查询中的代码

...
where (r.Status.Value == StatusEnum.Answered || r.Status.Value == StatusEnum.AwaitingResponse)
...

被翻译成

.Where(ti => (int)ti.Outer.Status.Value == 1 || (int)ti.Outer.Status.Value == 0)

它试图翻译的值属于这种类型:

    public class MyStatusClass<T> where T : Enum
    {
        public MyStatusClass(int i)
        {
            Value = (T)Enum.Parse(typeof(T), value.ToString());
            IntVal = i // This was added to simplify problem, see update above
        }

        public T Value { get; internal set; } // This is the field that I need stored in the database

        public int IntVal {get; internal set; } // This was added to simplify problem, see update above

        // Some other methods in here; the reason I converted from an enum to this class               
    }

我的 DbContext ModelBuilder 中的转换看起来像这样

entity.Property(x => x.Status)
    .HasConversion(
        status => status.Value,
        status => new StatusClass((int)status) // This is the part to focus on, as its' the part that tells EF how to read the property from the database
    );

0 个答案:

没有答案