The*_*ads 5 c# linq entity-framework
我已经尝试了一段时间,以寻找适合我要编写的linq查询的解决方案。
在我的模型结构中,我有Item类,其中包含PaymentRecords列表。我希望我的查询实现的是:
public class PaymentRecord
{
public int PaymentRecordId { get; set; }
[Required]
public double PaymentAmount { get; set; }
[Required]
public DateTime DateOfPayment { get; set; }
[Required]
public bool FinalPayment { get; set; }
[JsonIgnore]
public Item Item{ get; set; }
}
public class Item
{
public int ItemId { get; set; }
public List<PaymentRecord> PaymentRecords {get; set;}
...various other properties
}
Run Code Online (Sandbox Code Playgroud)
选择所有的项目,其中PaymentRecord列表符合以下条件(可以正常工作),或者PaymentRecord为null,例如Items类没有PaymentRecord。有没有办法做到这一点?
var result = m_context.Item
.SelectMany(
x => x.PaymentRecords.Where(p => (p.FinalPayment == true
&& p.DateOfPayment >= _revenueStatementRequest.StartDate
&& p.DateOfPayment <= _revenueStatementRequest.EndDate)
|| p.FinalPayment != true),
(x, p) => x
)
.ToList();
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想做以下类似的事情,但是我无法获得与工作类似的东西:
var result = m_context.Item
.SelectMany(
x => x.PaymentRecords.Where(p => (p.FinalPayment == true
&& p.DateOfPayment >= _revenueStatementRequest.StartDate
&& p.DateOfPayment <= _revenueStatementRequest.EndDate)
|| p.FinalPayment != true)
|| x.PaymentRecords == null,
(x, p) => x
)
.ToList();
Run Code Online (Sandbox Code Playgroud)
从给出的答案工作后,我有这个:
m_context.Item.Where(c => (!
c.PaymentRecords.Any(q => (q.FinalPayment &&
q.DateOfPayment >= _revenueStatementRequest.StartDate &&
q.DateOfPayment <= _revenueStatementRequest.EndDate)
|| q.FinalPayment != true
)
)
&& (c..Type == Booked || c.Type == Reserved)
&& (c.StartDate < _revenueStatementRequest.StartDate)
)
Run Code Online (Sandbox Code Playgroud)
你可以做到这一点,无需SelectMany
List<Item> res = m_context.Items
.Where(c => !c.PaymentRecords
.Any(q => (q.FinalPayment &&
q.DateOfPayment >=_revenueStatementRequest.StartDate &&
q.DateOfPayment <= _revenueStatementRequest.EndDate)
|| !q.FinalPayment)
)
//**EDIT**
.Where(c => c.StartDate < _revenueStatementRequest.StartDate)
//this is comment out, so we can better test on the more complex part of the query
//.Where(c => c.Type == Booked || c.Type == Reserved)
.ToList();
Run Code Online (Sandbox Code Playgroud)
这样你就得到了一个List<Item>
而不是List<PaymentRecord>