【问题标题】:LINQ to SQL error on .Join().Join() 上的 LINQ to SQL 错误
【发布时间】:2014-10-27 03:24:19
【问题描述】:

我正在尝试查询数据库并连接两个表。我从来没有以这种方式使用过 Join(),并且在第二个 Join() 上出现错误:

var adjustments = data.Inventory_ARCHIVEs
    .Where(i => i.Location == comboBox3.Text && 
        upcCodes.Contains(i.UPCCode) && 
        (i.AVtime.Value.Date >= dateTimePicker1.Value.Date && 
            i.AVtime.Value.Date <= dateTimePicker1.Value.AddDays(1).Date) && 
        (i.BVtime.Value.Date >= dateTimePicker1.Value.Date && 
            i.BVtime.Value.Date <= dateTimePicker1.Value.AddDays(1).Date))
    .GroupBy(i => new { i.UPCCode })
    .Select(i => new
    {
        ID = i.Max(x => x.ID),
        i.Key.UPCCode
    })
    .Join(data.Inventory_ARCHIVEs, a => a.ID, 
        b => b.ID, (a, b) => new { a, b })
    .Join(data.BQItems, x => new { x.a.UPCCode, x.b.Location }, 
        y => new { y.UPC_Code, y.Location }, (x, y) => new
    {
        ID = x.a.ID,
        UPCCode = x.a.UPCCode,
        Date = x.b.BVtime.Value.Date,
        Description = y.Description,
        BVamount = x.b.BVamount,
        AVamount = x.b.AVamount,
        Difference = x.b.AVamount - x.b.BVamount,
        AverageCost = x.b.AverageCost,
        ExtCost = (x.b.AVamount - x.b.BVamount) * x.b.AverageCost
    });

x.a.UPCCodex.b.Locationy.UPC_Codey.Location 是字符串。

这是错误:

方法 'System.Linq.Enumerable.Join 的类型参数 (System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable, System. Func, System.Func, System.Func)' 无法从用法中推断出来。尝试明确指定类型参数。

如果我不包括“位置”列的连接而只使用“UPCCode”,它可以工作,但是当我按列添加第二个连接时,我收到错误

【问题讨论】:

  • 多列join的关键点是:列类型必须相同,并且 列名也必须相同。

标签: c# sql database linq


【解决方案1】:

我怀疑这是问题所在 - 至少是一个问题:

.Join(data.BQItems, x => new { x.a.UPCCode, x.b.Location }, 
                    y => new { y.UPC_Code, y.Location },
                    ...)

您正在尝试使用两种不同匿名类型作为键类型来加入。他们有不同的属性——一个有UPCCode,另一个有UPC_Code。你可能想要:

.Join(data.BQItems, x => new { x.a.UPCCode, x.b.Location },
                    y => new { UPCCode = y.UPC_Code, y.Location },
                    ...)

或者只是与您的属性名称更加一致,以便您在任何地方都使用UPCCodeUPC_Code,而不是混合使用。

【讨论】:

  • 好人,谢谢。它解决了这个问题。这让我很失望,因为如果我不按“位置”加入,它会接受“UPCCode”和“UPC_Code”
  • @user2777664:如果你也使用匿名类型,那就不会了。当您只是使用 values (作为字符串或其他)时,那只是将字符串与字符串匹配,这很好。
【解决方案2】:

你必须最关心'equals'子句两边的数据类型,它们应该是相同的数据类型,如int和int,或者string和string。

或者使用 lambda 表达式,Join 子句中的第二个和第三个参数必须是相同的数据类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    相关资源
    最近更新 更多