我将 blazor (blazorise datagrid) 与 asp.net 核心和实体框架一起使用。我在尝试对具有外键列(复杂对象)的数据执行 crud 操作时遇到问题。这是我的代码
模型类
public partial class ApproverSequence
{
public int Id { get; set; }
public int? TransactionTypeId { get; set; }
public bool? IsStart { get; set; }
public bool? IsArchived { get; set; }
public virtual TransactionType TransactionType { get; set; }
}
public partial class TransactionType
{
public TransactionType()
{
ApproverSequences = new HashSet<ApproverSequence>();
}
public int Id { get; set; }
public string Description { get; set; }
public bool? IsArchived { get; set; }
public virtual ICollection<ApproverSequence> ApproverSequences { get; set; }
}
这是我的数据网格列
<DataGridSelectColumn TItem="ApproverSequence" Field="@nameof(ApproverSequence.TransactionType)" Caption="Description" Editable="true">
<DisplayTemplate>
@{
var transactionTypeDesc = (context as ApproverSequence).TransactionType?.Description;
@transactionTypeDesc
}
</DisplayTemplate>
<EditTemplate>
<Select TValue="int"
SelectedValue="@((int)((TransactionType)(((CellEditContext)context).CellValue)).Id)"
SelectedValueChanged="@( v => ((CellEditContext)context).CellValue = transactionTypes.First(x=> x.Id == v))">
@foreach (var item in transactionTypes)
{
<SelectItem TValue="int" Value="@(item.Id)">@item.Description</SelectItem>
}
</Select>
</EditTemplate>
</DataGridSelectColumn>
@code{
private List<ApproverSequence> approverSequences;
private List<TransactionType> transactionTypes;
protected override async Task OnInitializedAsync()
{
approverSequences = await ApproverSequenceService.GetAll();
transactionTypes = await TransactionTypeService.GetAll();
}
}
服务
public async Task<List<ApproverSequence>> GetAll()
{
try
{
return await _context.ApproverSequences.Include(x=>x.TransactionType).Where(x => x.IsArchived == false).ToListAsync();
}
catch
{
throw;
}
}
public async Task<List<TransactionType>> GetAll()
{
try
{
return await _context.TransactionTypes.Where(x => x.IsArchived == false).ToListAsync();
}
catch
{
throw;
}
}
运行此项目时,它会抛出 System.NullReferenceException: 'Object reference not set to an instance of an object。例外。有什么我错过的吗?提前致谢