【问题标题】:Adding Join to Existing LINQ Query将联接添加到现有 LINQ 查询
【发布时间】:2015-12-04 12:17:40
【问题描述】:

this Stack Overflow question 帮助我。

现在我正在构建查询,需要向其他表添加连接以引入名称和描述等。

我的查询是这样的:

using (var ctx = new myEntities())
            {
                var pc = ctx.tblPostcodes.Where(z => z.Postcode == postcodeOutward)
                        .Select(x => new {postcodeId = x.PostcodeID}).Single();

                int pcId = pc.postcodeId;

                var q = ctx.tblPrices.OrderByDescending(x => x.Cost)
                .Where(c => c.PostcodeID == pcId)
                .Where(s => s.ItemID < 18)
                .GroupBy(x => x.ItemID)
                .Select(g => new { g, count = g.Count() })
                .ToList()
                .SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) => new { j.ItemID, j.Cost, j.SupplierID }));

                foreach (var i in q)
                {
                    sb.AppendFormat("ItemId = {0}, Cost = {1}, SupplierId = {2}<hr/>", i.ItemID,  i.Cost, i.SupplierID);
                }
            }

我正在尝试添加以下联接:

.Join(ctx.tblItems, it => it.ItemID, s => s.ItemID, (it, s) => new { it, s })

但它会导致模棱两可的调用错误。有任何想法吗?我需要再添加两个内部连接。我希望能做对一个,另外两个会很容易(希望如此)。

【问题讨论】:

  • 你先用数据库?
  • 是的!我必须将其作为当前使用的。
  • 根据您的模型,您应该能够(在存储过程中)做“疯狂”的事情,例如:x.Address.PrimaryOwner.Name,Linq 将在后台处理所有必需的连接。表达输出,而不是你习惯的方式。
  • 新 { j.ItemID,j.Cost,j.SupplierID,j.tblItems.Name}。很酷...

标签: c# linq lambda


【解决方案1】:

如果您首先使用数据库,EF 会为您生成导航属性,因此您不必加入。

如果您希望能够在查询之外获取此信息,请使用 .Include("Navigational Propertyname") 命令添加您的“联接”,这将导致将相应的对象或对象列表添加到查询结果中.

 var q = ctx.tblPrices.Include("tblItems").OrderByDescending(x => x.Cost)

最好查看 EF 模型以找出属性的名称...

【讨论】:

  • 这对我来说是一分钱一分货,尤里卡时刻。谢谢你和@jessehourwing!
【解决方案2】:

试试这个,不知道第一次试试能不能用,不过是个不错的起点!

using (var ctx = new myEntities())
{
    var pc = ctx.tblPostcodes
        .First(x => x.Postcode == postcodeOutward)
        .Select(x => new { postcodeId = x.PostcodeID });

    var prices = ctx.tblPrices
        .Where(x => x.PostcodeID == pc.postcodeId)
        .OrderByDescending(x => x.Cost)
        .ToList();

    var items = ctx.tblItems
        .Where(y => y.ItemID < 18)
        .GroupBy(y => y.ItemID)
        .Select(y => new { y, count = y.Count() })
        .ToList();

    // Join
    var q = prices
        .Join(items,
            pr => pr.ItemID,
            it => it.ItemID,
            (pr, it) => new
            {
                pr.ItemID,
                pr.Cost,
                pr.SupplierID
            })
        .ToList();

    q.Select(x => sb.AppendFormat("ItemId = {0}, Cost = {1}, SupplierId = {2}<hr/>", 
        x.ItemID, x.Cost, x.SupplierID));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多