【问题标题】:C# Lambda with Entity Framework - Return a result even when no match带有实体框架的 C# Lambda - 即使不匹配也返回结果
【发布时间】:2015-04-22 21:57:30
【问题描述】:

下面的代码正在运行,但如果根据 where 子句找不到带有“域管理员”的条目,它将完全忽略该特定结果上的任何其他内容。这导致我缺少项目,因为我生成的视图可能没有“域管理员”条目。我知道这是因为它是一个明确的位置,但我不太确定如何准确地表示我需要做的事情。我怀疑我需要进行 LEFT JOIN,但不确定这会如何影响导航属性。任何正确方向的指导将不胜感激。

var endpointConstructor = db.tbl_equipment.Include(t => t.tbl_Backup_Configuration)
   .Where(e => e.tbl_Backup_Configuration.FirstOrDefault().BackupType == null)
   .Where(e => e.tbl_customer.Calc_Contract_Status == true && e.Calc_Contract_Status == true && e.Equip_type.Contains("server")).OrderBy(e => e.tbl_customer.Priority)
   .Where(what => what.tbl_customer.tbl_user_pass_list.FirstOrDefault().Usage1 == "Domain Administrator")
   .Select(s => new CompanyServerUserPassViewModel { Comp_ID = s.Comp_ID, ServerName = s.NetBIOS_name, AdminUsername = s.tbl_customer.tbl_user_pass_list.FirstOrDefault().Username,
   AdminPassword = s.tbl_customer.tbl_user_pass_list.FirstOrDefault().Password, Company = s.Company, TeamviewerID = s.tbl_computerinfo.FirstOrDefault().teamviewerID });

【问题讨论】:

  • FirstOrDefault().Password 作为旁注,您了解这里的“默认”是什么,如果您要求属性,它会抛出?
  • 是的 - 我假设它不存在时会抛出 null ?

标签: c# entity-framework lambda


【解决方案1】:

类似的东西:

.Where(what => [statement that evaluates to true if there is no domain admin] 
|| what.tbl_customer.tbl_user_pass_list.First().Usage1 == "Domain Administrator")

【讨论】:

  • 难道不是简单地评估所有内容从而使这条线毫无意义吗?如果我实际上删除了域管理员的 .Where 子句,它会返回我需要的所有内容,但是在域管理员不存在的项目上,它会在列表中使用另一种类型的用户名/密码填充我的视图。我想做的是如果它们是域管理员类型的值,则返回值,但如果没有任何域管理员类型的值,则返回 null。
  • "但是如果它无法根据 where 子句找到带有“域管理员”的条目,它将完全忽略该特定结果上的任何其他内容”我认为您希望它在这种情况下返回值没有域管理员。
  • 对不起,如果我不清楚,假设我有一家名为 Contoso Ltd 的公司和一个名为 SERVER1 的服务器。如果在域管理员的 tbl_user_pass 中有一个条目,我的代码可以正常工作并返回结果集中的所有内容,一切都很好。如果它没有域管理员,它将完全从结果集中发出 Contoso Ltd 和 Servername。现在 Contoso Ltd 可能在 tbl_user_pass 中有一个条目,例如打印机。如果我实现您的代码,它将返回 Contoso Ltd、SERVER1、PrinterUsername、PrinterPassword。我真正想要返回的是 Contoso Ltd, SERVER1, null, null。
  • 将 where's 移动到选择中?
  • 我发现您的用例有点令人困惑。我会回来看看我是否有时间。可能值得检查语法并将其简化为简化示例以吸引更多答案。
猜你喜欢
  • 2020-09-09
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 2019-08-20
  • 2012-04-10
  • 1970-01-01
相关资源
最近更新 更多