在Entity Framework Core中用LINQ加载子关联实体遇匿名类型错误
Hey there! Let's work through this issue you're hitting with Entity Framework Core. That error message about invalid anonymous type members almost always comes down to how you're defining properties in an anonymous object—usually missing a clear member assignment or using syntax EF can't parse.
First, Let's Understand the Root Cause
When you're projecting results (using Select to create anonymous or custom types), every member in the anonymous type needs to be either:
- A simple property name (like
q.Id), - A member access (like
a.AnswerType.Name), - Or explicitly assigned to a named property (like
AnswerType = a.AnswerType).
If you skip this naming (e.g., writing new { a, a.AnswerType } without labels), EF throws that exact error because it can't infer a valid member name for the second item.
Solution 1: Load Related Data with Include + ThenInclude
If you just need to return full Question entities with their Answers and linked AnswerType data, this is the simplest approach. EF will handle loading all nested relationships for you:
using Microsoft.EntityFrameworkCore; // Assuming _context is your DbContext instance var questionsWithAnswersAndTypes = await _context.Questions // Load the Answers collection for each Question .Include(question => question.Answers) // Then load the AnswerType for each Answer in the collection .ThenInclude(answer => answer.AnswerType) .ToListAsync();
Just make sure your entity classes have the correct navigation properties set up:
Questionclass:public ICollection<Answer> Answers { get; set; } = new List<Answer>();Answerclass:public AnswerType AnswerType { get; set; }+ foreign key property (e.g.,public int AnswerTypeId { get; set; })
Solution 2: Correctly Project to Anonymous/Custom Types
If you don't need full entity objects (e.g., you're returning a subset of data), you need to explicitly name every member in your nested anonymous types. Here's how to fix the projection:
Wrong (Causes the Error)
// ❌ Error: Anonymous type members need clear names var badResult = await _context.Questions .Select(q => new { q.Id, q.Title, Answers = q.Answers.Select(a => new { a, a.AnswerType }) // No names for nested members }) .ToListAsync();
Correct (Valid Anonymous Type Syntax)
// ✅ All nested members have explicit names var goodResult = await _context.Questions .Select(q => new { QuestionId = q.Id, QuestionTitle = q.Title, Answers = q.Answers.Select(a => new { AnswerId = a.Id, AnswerContent = a.Content, // Explicitly name the AnswerType object and its properties AnswerType = new { TypeId = a.AnswerType.Id, TypeName = a.AnswerType.Name } }) }) .ToListAsync();
Or if you want to include full Answer and AnswerType objects in the projection:
var fullResult = await _context.Questions .Select(q => new { Question = q, AnswersWithTypes = q.Answers.Select(a => new { Answer = a, AnswerType = a.AnswerType }) }) .ToListAsync();
Quick Check
Double-check your entity configurations to ensure EF recognizes the relationships between Question, Answer, and AnswerType. You can use data annotations (like [ForeignKey]) or fluent API in your DbContext to define these if needed.
内容的提问来源于stack exchange,提问作者K.Z

