[英]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.