在实体框架核心中包含集合 [英] Include collection in Entity Framework core

查看:96
本文介绍了在实体框架核心中包含集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个实体:

  public class Book 
{
[Key]
public string BookId {get;组; }
public List< BookPage>页面{get;组; }
public string Text {get;组;
}

public class BookPage
{
[Key]
public string BookPageId {get;组; }
public PageTitle PageTitle {get;组; }
public int Number {get;组;
}

public class PageTitle
{
[Key]
public string PageTitleId {get;组; }
public string标题{get;组; }
}

如果我只知道BookId,我应该如何加载所有的PageTitles? p>

这是我如何尝试这样做:

 使用(var dbContext = new BookContext())
{
var bookPages = dbContext
.Book
.Include(x => x.Pages)
.ThenInclude x => x.Select(y => y.PageTitle)
.SingleOrDefault(x => x.BookId ==some example id)
.Pages
。选择(x => x.PageTitle)
.ToList();
}

但问题是,它抛出异常


ArgumentException:属性表达式x => {从x中的页面y
中选择[y] .PageTitle}'无效。表达式应该代表
属性访问:'t => t.MyProperty'。当指定多个
属性时,使用匿名类型:'t => new {t.MyProperty1,
t.MyProperty2}'。参数名称:propertyAccessExpression


有什么问题,该怎么办?

解决方案

直接在 ThenInclude 中访问 PageTitle

  using(var dbContext = new BookContext())
{
var bookPages = dbContext
.Book
.Include(x => x.Pages)
.ThenInclude(y => y.PageTitle)
.SingleOrDefault(x => x.BookId ==some example id)
。选择(x => x.Pages)
.Select(x => x.PageTitle)
.ToList();
}


For example, I have this entities:

public class Book
{
    [Key]
    public string BookId { get; set; }
    public List<BookPage> Pages { get; set; }
    public string Text { get; set; }
} 

public class BookPage
{
    [Key]
    public string BookPageId { get; set; }
    public PageTitle PageTitle { get; set; }
    public int Number { get; set; }
}

public class PageTitle
{
    [Key]
    public string PageTitleId { get; set; }
    public string Title { get; set; }
}

How should I load all PageTitles, if I Knew only BookId?

Here it is how I'm trying to do this:

using (var dbContext = new BookContext())
{
    var bookPages = dbContext
    .Book
    .Include(x => x.Pages)
    .ThenInclude(x => x.Select(y => y.PageTitle))
    .SingleOrDefault(x => x.BookId == "some example id")
    .Pages
    .Select(x => x.PageTitle)
    .ToList();
}

But the problem is, that it throws exception

ArgumentException: The properties expression 'x => {from Pages y in x select [y].PageTitle}' is not valid. The expression should represent a property access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type: 't => new { t.MyProperty1, t.MyProperty2 }'. Parameter name: propertyAccessExpression

What's wrong, what exactly should I do?

解决方案

Try accessing PageTitle directly in ThenInclude:

using (var dbContext = new BookContext())
{
    var bookPages = dbContext
    .Book
    .Include(x => x.Pages)
    .ThenInclude(y => y.PageTitle)
    .SingleOrDefault(x => x.BookId == "some example id")
    .Select(x => x.Pages)
    .Select(x => x.PageTitle)
    .ToList();
}

这篇关于在实体框架核心中包含集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆