&安培;&安培; z.DisplayDurations.Count> 0这是场景。有2个实体类:
class DisplayDuration
{
public int DisplayDurationID { get; set; }
public double Seconds { get; set; }
public string SecondsString { get; set; }
public int? FK_Zone { get; set; }
public double? BasePrice { get; set; }
public bool? IsActive { get; set; }
}
class Zone
{
public int ZoneID { get; set; }
public int FK_ProductID { get; set; }
public string Name { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public bool Active { get; set; }
public string Description { get; set; }
public virtual List<DisplayDuration> DisplayDurations { get; set; } //Contains the list of DisplayDuration
}
现在当我尝试获取基于DisplayCount的区域列表时,所有DisplayDuration关于该zoneid所有DisplayDuration出现,而我只想要DisplayDuration与IsActive值&#34; True&#34;。有没有办法实现它。 我这样做。
public List<Zone> RetrieveActiveZonesHavingDDurations()
{
var zone = from z in _context.Zones
where z.Active && && z.DisplayDurations.Count > 0
select z;
return zone.ToList();
}
答案 0 :(得分:3)
由于无法过滤关联属性(即仅获取活动的DisplayDurations),并且无法在Linq-to-entities中构造实体,因此您需要匿名对象或模拟Zone的中间类。
public class ZoneModel
{
public int ZoneID { get; set; }
public int FK_ProductID { get; set; }
public string Name { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public bool Active { get; set; }
public string Description { get; set; }
public virtual IEnumerable<DisplayDuration> DisplayDurations { get; set; }
}
现在你可以这样做:
var zones = _context.Zones
.Where(z => z.Active && z.DisplayDuration.Count>0)
.Select(z => new ZoneModel
{
ZoneID = z.ZoneID,
FK_ProductID = z.FK_ProductID,
Name = z.Name,
Width = z.Width,
Height = z.Height,
Active = z.Active,
Description = z.Description,
DisplayDurations = z.DisplayDurations
.Where(d => d.IsActive.HasValue && d.IsActive.Value==true)
});
答案 1 :(得分:0)
更新您的方法,如下所示。
public List<Zone> RetrieveActiveZonesHavingDDurations()
{
var zone = from z in _context.Zones
where z.Active
&& z.DisplayDurations != null
&& z.DisplayDurations.Count > 0
&& z.DisplayDurations.Any<DisplayDurations>(x => x.IsActive == true)
select z;
return zone.ToList();
}