我正在使用 graphQL 熱巧克力并且需要獲取資料。我需要從具有規格的模板中獲取資料,并且在規格中它包含 AttributeType。當我嘗試查詢資料時,模板和規范有值,但 AttributeType 不應該是 null。這是我的物體:
模板
public long Id { get; set; }
public bool IsDeleted { get; set; }
public string Name { get; set; }
public long SpecId { get; set; }
public virtual List<Spec> Specs { get; set; }
規格
public long Id { get; set; }
public int Position { get; set; }
public string Label { get; set; }
public bool IsDeleted { get; set; }
public virtual AttributeType AttributeType { get; set; }
public long AttributeTypeId { get; set; }
public Template Template { get; set; }
public long? TemplateId { get; set; }
最后是 AttributeType
public long Id { get; set; }
public string Description { get; set; }
public string Format { get; set; }
我使用 Dataloader 和決議器來獲取資料
[Authorize]
[GraphQLType( typeof(TemplateObjectType) )]
public Task<Template> GetTemplateById( long id, TemplateDataLoader dataLoader, CancellationToken cancellationToken )
=> dataLoader.LoadAsync( id, cancellationToken );
public class TemplateObjectType: ObjectType<Template>
{
protected override void Configure( IObjectTypeDescriptor<Template> descriptor )
{
descriptor.Field( x => x.Specs)
.ResolveWith<TemplateResolver>( r => r.GetSpecsAsync( default, default, default ) );
}
}
public async Task<IReadOnlyList<Spec>> GetSpecAsync(
[Parent] Template template,
SpecDataLoader dataLoader,
CancellationToken cancellationToken)
=> await dataLoader.LoadAsync(template.Id, cancellationToken);
protected override async Task<ILookup<long, Spec>> LoadGroupedBatchAsync( IReadOnlyList<long> keys, CancellationToken cancellationToken )
{
var result = await _dbContext.Templates
.Where( template => keys.Contains( template.Id ) )
.Select( x => new {
TemplateId= x.Id,
x.Specs
} )
.ToListAsync( cancellationToken: cancellationToken );
var final = result
.Select(x => x.Specs.Select(c => new
{
x.TemplateId,
Spec= c
}))
.SelectMany(x => x)
.ToLookup(x => x.TemplateId, x => x.Spec);
return final;
}
當我查詢 GetTemplateById 時,我得到了結果,但AttributeType不應該是 null,這是查詢的示例:
"data": {
"templatebyId": {
"name": "test",
"specs": [
{
"id": 4,
"position": 0,
"label": "price",
"templateId": 1,
"attributeType": null
}
]
}
}
uj5u.com熱心網友回復:
默認情況下,EF 嘗試優化從資料庫中獲取的資料量。正如您的代碼現在一樣,未加載屬性。
您應該attributes在此呼叫中包含 或省略ToListAsync以讓 EF 確定您將在稍后階段需要資料。
var result = await _dbContext.Templates
.Where( template => keys.Contains( template.Id ) )
.Select( x => new {
TemplateId= x.Id,
x.Specs
} )
.ToListAsync( cancellationToken: cancellationToken );
使用Include/ThenInclude將告訴框架包含資料:
var result = await _dbContext.Templates
.Where( template => keys.Contains( template.Id ) )
.Include(prop => prop.Specs)
.ThenInclude(spec => spec.AttributeType)
.Select( x => new {
TemplateId= x.Id,
x.Specs
} )
.ToListAsync( cancellationToken: cancellationToken );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459879.html
標籤:C# 网 asp.net-mvc 图形 热可可
上一篇:根據查詢字串值激活li
