使用Entity Framework获取所需记录的多个条件

时间:2016-12-01 13:30:18

标签: c# .net entity-framework linq entity-framework-6

我试图从统计表中获取单个记录,其逻辑如下:

1st preference :  Flag = 0
2nd preference :  Flag = 1
3rd preference :  Flag = 2 (only if we dont have records with flag=0 and 1)

表:统计

Id   Zoneid  Emergency   Flag   Date
1    100      0           1     2016-6-01 13:10:05.360
2    100      2           2     2016-6-01 14:10:05.360
3    100      0           2     2016-6-01 15:10:05.360
4    100      2           2     2016-6-01 16:10:05.360
5    100      2           0     2016-6-01 14:10:05.360
6    100      1           2     2016-6-01 13:10:05.360

我试图实现的逻辑如下:

If(Flag == 0) then  
   take records with highest emergency(order by emergency desc) but if multiple records found then take latest record order by date desc(only 1 ).
else if(flag==1) 
     Take records with highest emergency(order by emergency desc) but if multiple records found then take latest record order by date desc(only 1).
else if (no records with flag==0 and flag==1 found)
    Take records with highest emergency(order by emergency desc) but if multiple records found then take latest record order by date desc(only 1).  

数据模型:

public partial class Zone
{
    public int Id { get; set; }
    public string Area { get; set; }
    public virtual ICollection<Statistics> Statistics { get; set; }
}

public partial class Statistics
{
    public int Id { get; set; }
    public int ZoneId { get; set; }
    public int Emergency { get; set; }
    public int Flag { get; set; }
    public System.DateTime Date { get; set; }
    public virtual Zone Zone { get; set; }
}

我的查询:

var statistics= (from z in db.Zone
                 select new 
                 {
                     ZoneName = z.Area,
                     //Not getting how t implement multiple conditions in EF
                     StatisticsId = z.Statistics.Where(t => t.ZoneId == 100 &&)
                                             .Select(t => t.Id).FirstOrDefault() 
                 }

所以在这里我没有得到如何实现所有这些条件并获得所需的统计记录。

2 个答案:

答案 0 :(得分:2)

您描述的逻辑听起来像简单的优先顺序 - 首先按public bool CanExecute() { return this.isIdle && this.someFlag && !this.CommandAbort.CanExecute(); } 升序,然后(等于Flag)按Flag降序,然后(等于EmergencyFlag)按Emergency降序,按顺序取第一条记录:

Date

答案 1 :(得分:1)

有一个镜头(警告:未经测试,没有时间重新创建课程和所有):

var statistics= (from z in db.Zone
                 select new 
                 {
                     ZoneName = z.Area,
                     StatisticsId = z.Statistics.OrderBy(t=>t.Flag)
                     .Where(t => t.ZoneId == 100).Select(t => t.Id).FirstOrDefault() 
                 });