EF LINQ查询:单行列展示客户及关联宠物信息与数量
解决EF LINQ一对多关联的聚合查询问题
嘿,我来帮你搞定这个查询需求!要把客户和他们的宠物信息整合成单行展示,关键是利用EF的投影和聚合函数来处理一对多的关联数据。
首先确认实体导航属性
确保你的Customer实体类已经定义了和Patient的一对多导航属性,比如:
public class Customer { public int Id { get; set; } public bool IsActive { get; set; } public string Tc { get; set; } public string Name { get; set; } public string Surname { get; set; } // 其他属性... public ICollection<Patient> Patients { get; set; } = new List<Patient>(); } public class Patient { public int Id { get; set; } public string Name { get; set; } public int CustomerId { get; set; } public Customer Customer { get; set; } // 其他属性... }
正确的EF LINQ查询语句
下面的查询会直接在数据库层面完成宠物名称的拼接和数量统计,然后映射到你的CustomerPageModel:
// 假设你有DbContext实例_context var customerList = await _context.Customers .Select(customer => new CustomerPageModel { id = customer.Id, isActive = customer.IsActive, tc = customer.Tc, name = customer.Name, surname = customer.Surname, email = customer.Email, address = customer.Address, phone = customer.Phone, note = customer.Note, accountID = customer.AccountId, // 用逗号分隔宠物名称,EF Core会自动翻译为数据库对应的聚合函数(比如SQL Server的STRING_AGG) pats = string.Join(", ", customer.Patients.Select(pet => pet.Name)), // 统计关联宠物数量 patCount = customer.Patients.Count() }) .ToListAsync();
关键说明
- 数据库层面聚合:EF Core 3.0及以上版本支持将
string.Join翻译为数据库原生的聚合函数(比如SQL Server的STRING_AGG、MySQL的GROUP_CONCAT),这样所有聚合操作都在数据库完成,性能更好。 - 空集合处理:如果某个客户没有宠物,
pats会是空字符串,patCount会是0,完全符合业务逻辑。 - 导航属性加载:不需要额外调用
Include(c => c.Patients),因为投影查询会自动触发EF加载关联的宠物数据,避免不必要的全量数据加载。
对应的返回模型定义
确保你的CustomerPageModel属性名称和查询里的映射一致:
public class CustomerPageModel { public int id { get; set; } public bool isActive { get; set; } public string tc { get; set; } public string name { get; set; } public string surname { get; set; } public string email { get; set; } public string address { get; set; } public string phone { get; set; } public string note { get; set; } public int accountID { get; set; } public string pats { get; set; } public int patCount { get; set; } }
这样执行查询后,就能得到你想要的JSON格式结果啦!
内容的提问来源于stack exchange,提问作者RaptorR
相关产品推荐
相关产品推荐

