来自不同类的 Lambda 表达式中的多个 Where 子句
Posted
技术标签:
【中文标题】来自不同类的 Lambda 表达式中的多个 Where 子句【英文标题】:Multiple Where clauses in Lambda expressions from different classes 【发布时间】:2021-09-04 05:18:08 【问题描述】:我创建了一个名为AppRequest的主类,在它之下,还有其他类Suspense、SuspenseDetails。 当我查询数据时,我想从 AppRequest 查询一个,从 Suspense 查询一个,从 SuspenseDetails 查询一个。
代码是这样写的
int y = int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
List<AppRequest> SuspencesforSettle = db.AppRequest.Where(s => s.Create_By == y).Where(s=> s.Status==true).ToList();
我想从 AppRequest 中查询 - CreatedBy 和 Status 并且还需要从 SuspenseDetails 中检查 Settle_Status。 但是,从 where 条件我只能获取 AppRequest 类下的字段。你们能帮我解决这个问题吗?
这就是我的模型设计的方式。
public class AppRequest
[Key]
public int Id get; set;
[Required]
[Display(Name = "Request Type")]
public int ReqType get; set;
[Required]
[Display(Name = "Requesting By")]
public int Req_By get; set;
[Required]
[Display(Name = "Requesting Date")]
public DateTime Req_Date get; set; = DateTime.Now;
[Required]
[Display(Name = "Request Location")]
public int Req_Location get; set;
[Required]
[Display(Name = "Request Heading")]
public string Req_Heading get; set;
[Display(Name = "Cover Note")]
public string Req_CoverNote get; set;
[Required]
[Display(Name = "Company Name")]
public int Company_Id get; set;
public bool Status get; set;
public int Create_By get; set;
public DateTime Created_Date get; set;
public int Modified_By get; set;
public DateTime Modified_Date get; set; = DateTime.Now;
public int Approval_Status get; set;
public virtual IList<Suspense> Suspense get; set;
public class Suspense
[Key]
public int Id get; set;
[Required]
[ForeignKey("AppRequest")]
public int Req_Id get; set;
public virtual AppRequest AppRequest get; set;
public virtual IList<SuspenseDetails> SuspenseDetails get; set;
public class SuspenseDetails
[Key]
public int Id get; set;
[Required]
[ForeignKey("Suspense")]
public int Sus_Id get; set;
public virtual Suspense Suspense get; set;
[Required]
[Display(Name = "Requesting Amount")]
public decimal Req_Amount get; set;
[Required]
[Display(Name = "Amount In Words")]
public string Req_Amount_In_Words get; set;
[Required]
[Display(Name = "Purpose")]
public string Purpose get; set;
[Required]
[Display(Name = "Cash Requesting for ")]
public int Req_For get; set;
public string Approved_Suspense_Id get; set;
public bool Cash_Issued get; set;
public int Cash_IssuedBy get; set;
public DateTime? Cash_Issued_Date get; set;
public bool Settled get; set;
【问题讨论】:
【参考方案1】:你可以这样写:
var result =
db
.AppRequest
.Where(appRequest => appRequest.Create_By == creator)
.Where(
appRequest =>
appRequest
.Suspense
.SelectMany(suspense => suspense.SuspenseDetails)
.Any(suspenseDetails => suspenseDetails.Settled)
)
.ToList();
【讨论】:
以上是关于来自不同类的 Lambda 表达式中的多个 Where 子句的主要内容,如果未能解决你的问题,请参考以下文章