如何在LINQ中返回连接语句

本文关键字:返回 连接 语句 LINQ | 更新日期: 2023-09-27 18:17:35

我想把结果3返回给主方法

 var result = (from od in orders
        join em in employees on od.EmployeeID equals em.EmployeeID
        join ct in customers on od.CustomerID equals ct.CustomerID
        //orderby em.EmployeeID
        select new
        {
            od.OrderID,
            od.ShipCountry,
            ct.CompanyName,
            ct.ContactName,
            FullName = em.FirstName + ' '+ em.LastName, 
        });

 var newOrders = result.OrderBy("OrderID DESC");
 var result3 = newOrders
    .ToList()
    .Skip(rowsPerPage * (page-1))
    .Take(rowsPerPage);
 return result3;
}
 public class MyJoin {
 public int OrderID { get; set; }
 public DateTime OrderDate { get; set; }
 public string ShipCountry { get; set; }
 public string CompanyName { get; set; }
 public string ContactName { get; set; }
 public string EmployeeName { get; set; }
 }

我不确定如何返回它作为一个简单的

return result3;

不起作用,我得到一个错误

不能隐式转换类型System.Collections.Generic.List<AnonymousType#1>System.Collections.Generic.List<UserQuery.MyJoin>

如何在LINQ中返回连接语句

它不工作,因为在这里:

select new
{
    od.OrderID,
    od.ShipCountry,
    ct.CompanyName,
    ct.ContactName,
    FullName = em.FirstName + ' '+ em.LastName, 
}

您正在创建新的类型-> AnonymouseType,并且它不是您期望在函数中返回的MyJoin类型。简单地使用:

select new UserQuery.MyJoin
{
   OrderID = od.OrderID,
   ...
}

当然您需要从MyJoin类中填充字段。

指定类型-

在你的情况下

IQueryable<UserQuery.MyJoin> result = (from od in orders
    join em in employees on od.EmployeeID equals em.EmployeeID
    join ct in customers on od.CustomerID equals ct.CustomerID
    //orderby em.EmployeeID
    select new UserQuery.MyJoin
    {
        od.OrderID,
        od.ShipCountry,
        ct.CompanyName,
        ct.ContactName,
        FullName = em.FirstName + ' '+ em.LastName, 
    });

不能从函数调用中返回匿名类型。

无论如何,您必须显式定义您期望的类型,然后

var result = (from od in orders
    join em in employees on od.EmployeeID equals em.EmployeeID
    join ct in customers on od.CustomerID equals ct.CustomerID
    //orderby em.EmployeeID
    select new UserQuery.MyJoin
    {
        od.OrderID,
        od.ShipCountry,
        ct.CompanyName,
        ct.ContactName,
        FullName = em.FirstName + ' '+ em.LastName, 
    });

var newOrders = result.OrderBy("OrderID DESC");
var result3 = newOrders
.Skip(rowsPerPage * (page-1))
.Take(rowsPerPage);
.ToList()
return result3;

注意,如果这是面向对象的Linq,或者DbContext对调用者可用,则不需要具体化结果(不需要. tolist())。