C# LINQ有条件地使用不同的字段进行连接

C# LINQ有条件地使用不同的字段进行连接,c#,entity-framework,linq,C#,Entity Framework,Linq,我有这样的情况: Table A Field A Field B d 1 d 2 d 3 Table B Field A Field B d 1 d 2 d 3 d 4 我希望表B中的“4”与表A中的“3”匹配。 这是我目前的代码: short maxFieldB = DatabaseContext.TableA .OrderByDescending(

我有这样的情况:

Table A 
Field A  Field B
   d       1 
   d       2
   d       3
Table B 
Field A  Field B
   d       1
   d       2
   d       3
   d       4
我希望表B中的“4”与表A中的“3”匹配。
这是我目前的代码:

short maxFieldB = DatabaseContext.TableA
    .OrderByDescending(x => x.FieldB)
    .Select(s => s.FieldB)
    .First();

IQueryable<FieldXType> fieldX = (from tableb in DatabaseContext.TableB
    join tablea in DatabaseContext.TableA on new 
    {
        a = tablea.FieldA,
        b = tablea.FieldB
    }
    equals new
    {
        a = tableb.FieldA,
        b = (tableb.FieldB > maxFieldB ? maxFieldB : tableb.FieldB)
    })
    .ToList();
我以为我在做与T-SQL CASE语句等效的事情。我做错了吗?如果是,我如何使“表B”上的“4”与“表A”上的“3”匹配?这是否与我从LAMBDA语法转换到中间的查询语法有关?


提前谢谢。

好的,就我理解你的问题而言,你有两个表,你想在多种条件下加入它们。 错误是正确的
“参数类型不匹配”。
以下是代码的几个问题:

IQueryable<FieldXType> fieldX = (from tableb in DatabaseContext.TableB
        join tablea in DatabaseContext.TableA on new Eaxmple1 //add a type name that contains defination for a and b
        {
            a = tablea.FieldA,
            b = tablea.FieldB//This is of some type say FieldB(as defined in your Model Eaxmple1)
        }
        equals new Eaxmple1 
        {
            a = tableb.FieldA,
            b = (tableb.FieldB > maxFieldB ? maxFieldB : tableb.FieldB) //and this maxFieldB is of another type 'short' as you defined above.
        } select tablea).ToList();

如果您能提供表格的更多详细信息,我可以提供更好的帮助。

您没有提供足够的数据来回答这个问题。FieldA和FieldB是什么类型的?通常,如果字段a和字段B不匹配,这应该是编译时错误,但我知道EF Core中有很多新的错误,您使用EFCore吗?字段a是字符串,字段B是短字符。使用EF 6.
join tablea对我来说是可疑的。tablea来自哪里?不应该是
加入DatabaseContext.TableA
?你是正确的@AdamSimon。我犯了一个错误,将此代码泛化以隐藏我的业务详细信息。更正。我看到另一个特定问题:tablea.FieldB>maxFieldB始终为false,因为tablea中的MAX(FieldB)小于tableb中的MAX(FieldB)。你的情况应该改变。
IQueryable<FieldXType> fieldX = (from tableb in DatabaseContext.TableB
        join tablea in DatabaseContext.TableA on new Eaxmple1 //add a type name that contains defination for a and b
        {
            a = tablea.FieldA,
            b = tablea.FieldB//This is of some type say FieldB(as defined in your Model Eaxmple1)
        }
        equals new Eaxmple1 
        {
            a = tableb.FieldA,
            b = (tableb.FieldB > maxFieldB ? maxFieldB : tableb.FieldB) //and this maxFieldB is of another type 'short' as you defined above.
        } select tablea).ToList();
public class Eaxmple1
{
public field a {get;set;}
public field b {get;set;}
}