我使用c#和linq2db,并具有以下类/表层次结构:
public class YearlyTemplate
{
[Column]
public int Id { get; set; }
public List<MonthlyTemplate> MonthlyTemplates { get; set;}
}
public class MonthlyTemplate
{
[Column]
public int Id { get; set; }
[Column]
public int YearlyTemplateId { get; set; }
public YearlyTemplate YearlyTemplate{ get; set; }
public List<DailyTemplate> DailyTemplates { get; set;}
}
public class DailyTemplate
{
[Column]
public int Id { get; set; }
[Column]
public int MonthlyTemplateId { get; set; }
public MonthlyTemplate MonthlyTemplate { get; set; }
}
public class AppDataConnect : DataConnection
{
public ITable<YearlyTemplate> YearlyTemplates => GetTable<YearlyTemplate>();
public ITable<WeeklyTemplate> WeeklyTemplates => GetTable<WeeklyTemplate>();
public ITable<DailyTemplate> DailyTemplates => GetTable<DailyTemplate>();
}我希望使用where语句从数据库中获取特定年份,但希望获取它的所有嵌套MonthlyTemplates和每个DailyTemplates模板的所有Monthlytemplate。我怎样才能有效地使用linq2db来做到这一点呢?我想我应该使用group by,但它只能在一个级别的深度上工作。
发布于 2020-08-05 22:24:48
这里没什么特别的。就像在EF核心中一样,linq2db包含用于快速加载的方法。首先,您必须定义关联
public class YearlyTemplate
{
[Column]
public int Id { get; set; }
[Association(ThisKey = nameof(YearlyTemplate.Id), OtherKey = nameof(MonthlyTemplate.YearlyTemplateId))]
public List<MonthlyTemplate> MonthlyTemplates { get; set;}
}
public class MonthlyTemplate
{
[Column]
public int Id { get; set; }
[Column]
public int YearlyTemplateId { get; set; }
public YearlyTemplate YearlyTemplate{ get; set; }
[Association(ThisKey = nameof(MonthlyTemplate.Id), OtherKey = nameof(DailyTemplate.MonthlyTemplateId))]
public List<DailyTemplate> DailyTemplates { get; set;}
}And查询
var query =
from y in db.YearlyTemplates
.LoadWith(yt => yt.MonthlyTemplates)
.ThenLoad(mt => mt.DailyTemplates)
where y.Id == 1
select y;
var result = query.ToArray();或使用过滤器(如何自定义LoadWith/ThenLoad的两种方式)
var query =
from y in db.YearlyTemplates
.LoadWith(yt => yt.MonthlyTemplates.Where(mt => !mt.IsDeleted))
.ThenLoad(mt => mt.DailyTemplates, q => q.Where(ti => !dt.IsDeleted))
where y.Id == 1
select y;
var result = query.ToArray();或者,您可以使用自定义投影,因为您只能选择所需的字段,因此性能会更好:
var query =
from y in db.YearlyTemplates
where y.Id == 1
select new
{
Id = y.Id,
MonthlyTemplates = y.MonthlyTemplates.Select(mt => new {
mt.Id,
DailyTemplates = mt.DailyTemplates.ToArray()
}).ToArray()
};
var result = query.ToArray();https://stackoverflow.com/questions/63150864
复制相似问题