使用Entity Framework连接多个表

时间:2012-10-30 15:05:39

标签: c# linq entity-framework

我正在尝试使用EF加入3个表,但它会抛出错误说

consider swaping conditions on either side of equals

可以请一些人帮助

 var billdata = from billtotal in context.billTotals
                                   join billcard in context.billClubcards
                                       on billtotal.OrderID equals billcard.OrderID

                                   join billtender in context.billTenders
                                       on billtender.OrderID equals billtotal.OrderID


                                   select billtotal;

2 个答案:

答案 0 :(得分:13)

编译错误非常正确: -

The name 'billtender' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.

您加入的桌子需要在左侧,您加入的桌子需要在右侧。因此: -

var billData =
    from billtotal in context.billTotals
    join billcard in context.billClubcards
        on billtotal.OrderId equals billcard.OrderId
    join billtender in context.billTenders
        on billtotal.OrderId equals billtender.OrderId
    select billtotal;

如果您想知道原因,那是因为查询语法只是底层扩展方法的语法糖: -

context.billTotals
  .Join(
    context.billClubcards,
    billtotal => billtotal.OrderId,
    billclubcard => billclubcard.OrderId,
    (billtotal, billclubcard) => billtotal)
  .Join(
    context.billTenders,
    billtotal => billtotal.OrderId,
    billtender => billtender.OrderId,
    (billtotal, billtender) => billtotal);

您的原始实施将扩展为: -

context.billTotals
  .Join(
    context.billClubcards,
    billtotal => billtotal.OrderId,
    billclubcard => billclubcard.OrderId,
    (billtotal, billclubcard) => billtotal)
  .Join(
    context.billTenders,
    billtotal => billtender.OrderId, // billtender isn't in scope!
    billtender => billtotal.OrderId, // billtotal isn't in scope!
    (billtotal, billtender) => billtotal);

答案 1 :(得分:0)

您加入的表的属性需要位于等于

的右侧

开关

来自:on billtender.OrderID equals billtotal.OrderID

至:on billtotal.OrderID equals billtender.OrderID