添加到现有LINQ查询的连接

时间:2014-12-16 11:37:48

标签: c# linq lambda

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 })

但它会导致模糊的调用错误。有任何想法吗?我需要再添加两个内连接。我希望得到一个正确,另外两个将是容易的(希望)。

2 个答案:

答案 0 :(得分:3)

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

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

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

更好地了解EF模型以找出属性的名称......

答案 1 :(得分:1)

试试这个,我不知道它是否会在第一次尝试时起作用,但这是一个很好的起点!

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));
}