【问题标题】:How to include sub class如何包含子类
【发布时间】:2013-04-07 12:26:07
【问题描述】:

有人可以帮我解决这个 dot .net mvc 问题吗:

我有这些课程:

public class ImportItem
{
    [Key]
    public int Id { get; set; }
}

public class ImportItemListTemplate
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public List<ImportItem> ImportItemList { get; set; }
}

public class Context : DbContext
{
    public DbSet<ImportItemListTemplate> ImportItemListTemplates { get; set; }
}

在控制器中我需要设置这个:

Context context = new Context();
int id = ...;
ImportItemListTemplate tmp = context.ImportItemListTemplates.Find(id);

但这不包括 ImportItemListTemplate 类中的 ImportItemList。我想我需要包含属性 ImportItemList,但我不知道如何。

我尝试了一些类似的想法:

ImportItemListTemplate tmp = context.ImportItemListTemplates.Include(i => i.ImportItemList).SingleOrDefault(x => x.Id == id);

但它不起作用。错误:

"无法将 lambda 表达式转换为类型 'string',因为它不是 委托类型”

非常感谢您的帮助。

【问题讨论】:

标签: c# asp.net-mvc entity-framework include


【解决方案1】:

您的代码应如下所示,

ImportItemListTemplate tmp = context.ImportItemListTemplates.Include("ImportItemList").SingleOrDefault(x => x.Id == id);

【讨论】:

  • 非常感谢!就是这样。-)
  • 另外一个问题:假设我在 ImportItem 类中有另一个属性(属于我的类 - DbTbl)。我也想包括它。我尝试了这样的想法: ImportItemListTemplate tmp = context.ImportItemListTemplates.Include("ImportItemList").Include("DbTbl").SingleOrDefault(x => x.Id == id);但身份证不起作用。我想,如果该属性处于同一级别(ImportItemListTemplates 类的属性),而不是在此级别之下,那将是可以的。我也会非常感谢这个回复。
  • 亲爱的 Petr,您必须在 ImportItemListTemplate 类中添加一个导航属性。看起来像public virtual List&lt;DbTbl&gt; DbTbls { get; set; } 更多信息你可以试试这个link
【解决方案2】:

试试这个:

ImportItemListTemplate tmp = context.ImportItemListTemplates
                                    .Include(i => i.ImportItemList)
                                    .Where(x => x.Id)
                                    .SingleOrDefault();

【讨论】:

  • 感谢您的快速回答。 Uzmanim.Net 的答案是我正在寻找的 - 只是字符串属性名称。您的解决方案中存在与我相同的错误(如果我理解良好的话)。
【解决方案3】:

DbSet.Include 接受一个字符串,因此它不会对 lambda 感到满意。

我猜你需要的是System.Data.Entity 命名空间中的IQueryable&lt;T&gt;.Include 扩展方法,尤其是接受表达式的overload。有了它,您可以使用类似

的语法
query.Include(e => e.Level1Collection)

从数据库中加载集合属性。
如果命名空间未添加到using 列表中,请添加命名空间,然后重试代码。

【讨论】:

  • 感谢您的快速回复。没错 - 我不能使用 lambda。 Uzmanim.Net 解决方案很明确,正是我想要的。
  • 我添加了这个命名空间,现在可以了。-) 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多