我有两个与数据库实体相关的实体。我已经像这样设置了模型以及我的
ApplicationDbContext
。但是,当我尝试对其运行查询以从相关实体获取数据时,我收到此错误。
System.InvalidOperationException:可为 Null 的对象必须有一个值。`
我怎样才能让它发挥作用?
查询
var fixtures = await _context.Fixtures
.Where(i => i.HomeTeam.Id == seasonteamid || i.AwayTeam.Id == seasonteamid)
.Select(i => new Match
{
ReferenceId = i.Id,
MatchType = MatchType.League,
DateTime = i.SeasonCalendarDate.Date,
DateName = i.SeasonCalendarDate.Name,
MatchDetails = i.Division.Name,
HomeTeamName = i.HomeTeam.TeamName,
AwayTeamName = i.AwayTeam.TeamName,
HomeTeamId = i.HomeTeam.Id,
AwayTeamId = i.AwayTeam.Id,
HomeFrameScore = i.Result.HomeScore,
AwayFrameScore = i.Result.AwayScore,
MatchStatus = i.MatchStatus,
LeagueId = i.League.Id
}).ToListAsync();
夹具.cs
public class Fixture
{
public long Id { get; set; }
public DateTime Date { get; set; }
public League League { get; set; }
public Season Season { get; set; }
public Result Result { get; set; }
//Properties omitted for brevity
}
结果.cs
public class Result
{
public long Id { get; set; }
public League League { get; set; }
public SeasonDivision Division { get; set; }
public SeasonCalendarDate SeasonCalendarDate { get; set; }
public Fixture Fixture { get; set; }
//Properties omotted for brevity
}
ApplicationDbContext.cs
builder.Entity<Result>()
.HasOne(i => i.Fixture)
.WithOne(a => a.Result)
.HasForeignKey<Fixture>(c => c.Id);
您的问题似乎不是加载导航属性,因为您在选择部分中使用了它们并且它们的值为 Null,您面临此错误
var fixtures = await db.Fixtures
.Include(r => r.Result)
.Include(r => r.SeasonCalendarDate)
.Include(r => r.Division)
.Include(r => r.HomeTeam)
.Include(r => r.AwayTeam)
.Select(i => new
{
ReferenceId = i.Id,
MatchType = MatchType.League,
DateTime = i.SeasonCalendarDate.Date,
DateName = i.SeasonCalendarDate.Name,
MatchDetails = i.Division.Name,
HomeTeamName = i.HomeTeam.TeamName,
AwayTeamName = i.AwayTeam.TeamName,
HomeTeamId = i.HomeTeam.Id,
AwayTeamId = i.AwayTeam.Id,
HomeFrameScore = i.Result.HomeScore,
AwayFrameScore = i.Result.AwayScore,
MatchStatus = i.MatchStatus,
}).ToListAsync();;