在 Entity Framework 核心中加载多级相关数据未按预期工作
Loading multiple levels of related data in Entity Framework Core not working as expected
我想急切地加载一些与 Article
对象相关的数据。
return await context.Articles
.Include(x => x.ArticleTags)
.ThenInclude(x => x.Tag)
// .ThenInclude(x => x.Value)
.Include(x => x.Author)
.ThenInclude(x => x.UserInfo)
.Include(x => x.Approver)
.ThenInclude(x => x.UserInfo)
.Include(x => x.Rejecter)
.ThenInclude(x => x.UserInfo)
.Include(x => x.LinkSubmitter)
.ThenInclude(x => x.UserInfo)
.FirstOrDefaultAsync(x => x.Id == id);
在此文章对象中,所有显示的属性都可以为null 或为空。 e.g. no tags, no author, no approver .. etc.
查询按原样工作(注释掉的行)。
但是,如果我包含嵌套的 ThenInclude()
,它会失败并出现错误:
System.ArgumentNullException: Value cannot be null. Parameter name: source
我认为这是因为这篇文章没有标签,它试图急切地加载不存在的标签的值。我将如何急切地加载文章可能存在或不存在的所有标签数据?
尝试.Include(x => x.ArticleTags.Tag?.Value)
我想急切地加载一些与 Article
对象相关的数据。
return await context.Articles
.Include(x => x.ArticleTags)
.ThenInclude(x => x.Tag)
// .ThenInclude(x => x.Value)
.Include(x => x.Author)
.ThenInclude(x => x.UserInfo)
.Include(x => x.Approver)
.ThenInclude(x => x.UserInfo)
.Include(x => x.Rejecter)
.ThenInclude(x => x.UserInfo)
.Include(x => x.LinkSubmitter)
.ThenInclude(x => x.UserInfo)
.FirstOrDefaultAsync(x => x.Id == id);
在此文章对象中,所有显示的属性都可以为null 或为空。 e.g. no tags, no author, no approver .. etc.
查询按原样工作(注释掉的行)。
但是,如果我包含嵌套的 ThenInclude()
,它会失败并出现错误:
System.ArgumentNullException: Value cannot be null. Parameter name: source
我认为这是因为这篇文章没有标签,它试图急切地加载不存在的标签的值。我将如何急切地加载文章可能存在或不存在的所有标签数据?
尝试.Include(x => x.ArticleTags.Tag?.Value)