var data = db.orderInfo.Join(db.orderType,
t => t.orderTypeId, // orderInfo表的连接键
s => s.id, // orderType表的连接键
(t, s) => new { t, s }) // 连接后的匿名类型
.OrderByDescending(x => x.t.orderId) // 按orderId降序排列
.Select(x => new
{
orderId = x.t.orderId, // 选择orderId字段
orderTypeName = x.s.name // 选择orderTypeName字段
// ...其他需要选择的字段
}).ToList(); // 转换为列表
在上述代码中,Join
方法用于连接两个表,OrderByDescending
方法用于按orderId
降序排列,Select
方法用于选择需要的字段。
LINQ查询是延迟执行的,这意味着在调用ToList
、ToArray
等方法之前,查询不会实际执行。因此,你可以在调用这些方法之前动态地修改查询。
var query = db.orderInfo.Join(db.orderType,
t => t.orderTypeId, // orderInfo表的连接键
s => s.id, // orderType表的连接键
(t, s) => new { t, s }) // 连接后的匿名类型
.OrderByDescending(x => x.t.orderId) // 按orderId降序排列
.Select(x => new
{
orderId = x.t.orderId, // 选择orderId字段
orderTypeName = x.s.name // 选择orderTypeName字段
// ...其他需要选择的字段
});
// 根据条件动态添加Where条件
if (someCondition)
{
query = query.Where(x => x.orderId > 100); // 示例条件:orderId大于100
}
var data = query.ToList(); // 转换为列表