实体框架虚拟ICollection如何查询

时间:2014-10-28 13:17:32

标签: c# entity-framework

首先,我是Entity Framework等的新手并尝试解决一些问题。我有这样的模型:

 public class EventInstance {

    [Column("EVENT_INSTANCE_ID")]
    public int EventInstanceID { get; set; }

    [Column("CUSTOMER_ID")]
    public int CustomerID { get; set; }

    [Column("EVENT_ID")]
    public int EventID { get; set; }

    [Column("START_DATE_TIME")]
    public System.DateTime StartDateTime { get; set; }

    public virtual Event Event { get; set; }

}

我需要访问名为EventTimeEventInstances的表中的属性,但该表未包含在模型中。我有两个问题。

如果我添加:

public virtual ICollection<EventTimeEventInstance> EventTimeInstances { get; set; }

这会影响我们申请的其他方面吗?

其次,如何在如下查询中从ICollection访问该属性:

 public IQueryable<EventInstance> GetInstances(int scheduleID) {
            // only returning instances that are 3 months back
            DateTime dateRange = DateTime.Now.AddDays(-180);
            return EventDBContext.EventInstances.Where
                (x => x.CustomerID == MultiTenantID && x.StartDateTime >= dateRange)
                .OrderBy(x => x.StartDateTime).AsQueryable();
        }

我需要能够将EventTimeInstances.EventTimeID == scheudleID添加到此查询中。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以在查询中使用它:

public IQueryable<EventInstance> GetInstances(int scheduleID) 
{
    // only returning instances that are 3 months back
    DateTime dateRange = DateTime.Now.AddDays(-180);
    return EventDBContext.EventInstances.Where(x => 
            x.CustomerID == MultiTenantID && 
            x.StartDateTime >= dateRange && 
            x.EventTimeInstances.Any(a => a.EventTimeID == scheudleID) ).OrderBy(x => x.StartDateTime).AsQueryable();
}