[英]Why can't I use an actual class in LINQ-to-SQL join method?
我正在尝试在 C#(使用 EntityFramework Core 3.1.13)中执行 LINQ 连接,该连接在密钥选择器中使用 class。
例如:
public class KeyClass {
public int Key { get; set; }
}
using (var Context = new ...Context()) {
var Query = Context.Table1.Join(Context.Table2,x => new KeyClass () { Key = x.ID }, x => new KeyClass() { Key = x.ID2 }, (x,y) => new { x, y });
}
当我使用 KeyClass 时它不起作用 - 我收到一条错误消息,指出无法翻译 LINQ 表达式。
但是,如果我改用匿名类型,它就可以正常工作:
using (var Context = new ...Context()) {
var Query = Context.Table1.Join(Context.Table2,x => new { Key = x.ID }, x => new { Key = x.ID2 }, (x,y) => new { x, y });
}
在我的情况下,我不能使用匿名类型,因为我希望能够在运行时动态构建连接,并且需要为键选择器使用发出的类型,因为它可能有多个键和不同的类型。
原因是 EFC 翻译器仅支持使用 arguments 而不是Expression.MemberInit
(C# object 初始化程序)的Expression.New
(C# new
) 构造函数调用作为连接键。
匿名类型和元组都属于第一类(事件虽然在语法上匿名类型分配看起来像 object 初始化程序,但实际上它是编译器生成的 class 的构造函数调用 - 类似于 C#9 记录声明),而您的 ZA2F2ED4F1010B61DZC 没有吨。
知道了这一切,解决方案实际上非常简单 - 只需向 class 添加和使用构造函数,例如
public class KeyClass
{
public KeyClass(int key) => Key = key;
public int Key { get; }
}
或在 C#9 中
public record KeyClass(int Key);
现在这有效(翻译)
var Query = Context.Table1.Join(Context.Table2,
x => new KeyClass(x.ID), x => new KeyClass(x.ID2),
(x, y) => new { x, y });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.