【问题标题】:Include multiple tables with EntityFramework使用 EntityFramework 包含多个表
【发布时间】:2017-05-30 12:59:42
【问题描述】:

我有 3 个如下图所示的表格

我在 c# 上有实体框架 codefirst 模型(自动生成)

我正在尝试从包含每个元素的附件列表的实体中获取 IEnumerable,并且我希望每个附件的附件类型都包含这些附件元素。

为了更好的演示,我需要:

IEnumerable<Registry> registries = GetTableData();
string oneofthedesiredname = registries
.First()
.Attachments
.First()
.AttachmentType.Name; //I want that, this definition works but its null

用GetTableData()方法就像

public IEnumerable<Registry> GetTableData()
    {
        IQueryable<Registry> _registries = _entities.Registry;
        IEnumerable<Registry> data;
        data = _registries
        .Where(p=>p.IsDeleted==false)
        .Include(p=>p.Attachments.Where(x=>x.IsDeleted==false))
        .AsEnumerable();//this query should have change because I cant get Attachmenttypes from this            
        return data;
    }

谢谢大家,感谢您的帮助。

【问题讨论】:

  • 也许我是盲人,但我找不到从 Rgistries 到 Attachments 的方法,因为只有 Attachments 知道注册表。能否请您发布您的 EF 代码模型?

标签: c# .net entity-framework linq


【解决方案1】:

您还必须在查询中为 AttachmentType 添加额外的 Include。

public IEnumerable<Registry> GetTableData()
{
    IQueryable<Registry> _registries = _entities.Registry;

    IEnumerable<Registry> data = _registries
        .Include(x => x.Attachments)
        .Include("Attachments.AttachmentType")
         // here do necessary filtering with Where()
         // ...

    return data;
}

【讨论】:

    【解决方案2】:

    使用此功能

    public IEnumerable<Registry> GetTableData()
        {
            IQueryable<Registry> _registries = _entities.Registry,where(m=>m.IsDeleted==false);
            IEnumerable<Registry> data;
            data = _registries     .Include(p=>p.Attachments.Where(x=>x.IsDeleted==false)).
     include(p=>p.AttachmentType).AsEnumerable();
            return data;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 2015-07-25
      • 2014-11-29
      相关资源
      最近更新 更多