[英]EF Core: How to load data from a table and related tables in Generic Repository
[英]How to get data from related table with EF core?
我正在從事網絡項目,我使用代碼優先方法在機器模型和實驗模型之間創建了一對多關系。 這是代碼:
public class Experiment
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreationDateTime { get; set; }
public string Path { get; set; }
public string Description { get; set; }
[ForeignKey("Machine")]
public int MachineId { get; set; }
public Machine Machine { get; set; }
}
public class Machine
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public ICollection<Experiment> Experiments { get; set; }
}
我可以通過 userId 過濾所有的實驗:
public async Task<IList<Experiment>> GetExperimentsAsync(int userId)
{
var experiments = await _experimentsDbContext.Experiments
.Where(x => x.UserId == userId)
.ToListAsync();
return experiments;
}
但是我收到machine = null,我需要做的是按userId過濾實驗列表並包含相關的機器對象,但我不能這樣做。
您需要使用 .Include() 方法明確指定要加載相關數據。
請查看MS 文檔
例子:
public async Task<IList<Experiment>> GetExperimentsAsync(int userId)
{
var experiments = await _experimentsDbContext.Experiments
.Where(x => x.UserId == userId)
.Include(e => e.Machine)
.ToListAsync();
return experiments;
}
試試下面的代碼:
public async Task<IList<Experiment>> GetExperimentsAsync(int userId)
{
var experiments = await _experimentsDbContext.Experiments
.Include(experiment => experiment.Machine)
.Where(x => x.UserId == userId)
.ToListAsync();
return experiments;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.