【问题标题】:includes() functions doesn't works包含()函数不起作用
【发布时间】:2014-05-23 21:54:23
【问题描述】:

我使用的是 EF 6 和 Code First,但由于某种原因,当我尝试从数据库中收集 ICB 列表时,依赖项(例如 Station)不会作为填充对象(icb.station)返回,只有电台 ID。我有这种关系。

公共类ICB {

    public ICB()
    {
        ICBResources = new List<ICBResource>();
    }

    public int ICBId { get; set; }

    public int LevelId { get; set; }
    public virtual Station Station { get; set; }
    public string Location { get; set; }
    public DateTime TimeOfCall { get; set; }
    public DateTime TimeStarted { get; set; }

    public Staff IncidentCommander { get; set; }
    public Staff OperationsCommander { get; set; }
    public Staff SectorCommander { get; set; }
    public Staff SectorCommander2 { get; set; }
    public Staff CommandSupportOfficer { get; set; }
    public Staff SafetyOfficer { get; set; }
    public Staff CommunicationsOfficer { get; set; }
    public Staff WaterOfficer { get; set; }
    public Staff BAOfficer { get; set; }
    public Staff HazmatOfficer { get; set; }



    public virtual Company Company { get; set; }

}

我应该怎么做才能让所有这些成员都被填满?他们只是想出 ID。 我正在使用 .Include() 但不起作用。

    public List<ICB> GetAllICBs(Company company, Station station = null)
    {
        if (station != null)
        {
            return GetDbSet<ICB>()
                .Include("ICBResources")
                .Include("Station")
                .Where(i => i.Company.CompanyId == company.CompanyId 
                    && i.Station.StationId == station.StationId)
                .OrderByDescending(o => o.TimeStarted).ToList();
        }
        else
        {
            return GetDbSet<ICB>()
                .Include("ICBResources")
                .Include("Station")
                .Where(i => i.Company.CompanyId == company.CompanyId)
                .OrderByDescending(o => o.TimeStarted).ToList();
        }
    }

【问题讨论】:

    标签: c# entity-framework ef-code-first linq-to-entities


    【解决方案1】:

    您好,您的存储库中有 GetDbSet 方法吗?如果是,它可能返回没有相关表的数据,您应该在存储库中使用 Include 更早的部分,即:

    IQueryable icb = db.ICB.Include("ICBResources");
    

    【讨论】:

    • 这是我的 dbContext protected TargetDbContext Context { get { return (TargetDbContext) UnitOfWork; } } protected virtual DbSet&lt;TEntity&gt; GetDbSet&lt;TEntity&gt;() where TEntity : class { return Context.Set&lt;TEntity&gt;(); }
    • 因此您需要为 ICB 创建自定义存储库,否则将无法正常工作
    • 我创造了那个。这个方法GetAllICBs 就是从那个开始的。我有这个 .Include() 适用于其他情况并且效果很好。我检查了我的模型,但由于某种原因,仅在 ICB 中不起作用。
    【解决方案2】:

    我在 include 方法上的属性名称错误。

    感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多