【EF】查询部分列数据 使用匿名类型

使用Lambda表达式

//创建上下文
DataModelContainer dbContext = new DataModelContainer();

//查询 用户ID,用户名,用户订单数
var data = dbContext.UserInfo
    .Select(u => new { u.Id, u.Name, orderCount = u.OrderInfo.Count });

foreach (var item in data)
{
    Console.WriteLine(item.Id + " " + item.Name + " " + item.orderCount);
}

使用Linq表达式

var data = from u in dbContext.UserInfo
           select new { u.Id, u.Name, orderCount = u.OrderInfo.Count };

 

看看生成的sql脚本

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name], 
    (SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[OrderInfo] AS [Extent2]
        WHERE [Extent1].[Id] = [Extent2].[UserInfoId]) AS [C1]
    FROM [dbo].[UserInfo] AS [Extent1]

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页