【发布时间】:2022-02-08 20:56:44
【问题描述】:
我有一个使用 EF Core 创建的模型(代码优先),我的一个属性尝试访问延迟加载的代理,如下所示:
public class T012_Pedido
{
private string _t012NumeroPedido;
private ObservableCollection<T012_Pedido_Item> _t012PedidoItem = new();
[Required]
[Column(TypeName = "varchar")]
[MaxLength(16)]
public string T012_NumeroPedido
{
get => this._t012NumeroPedido;
set
{
if (value == this._t012NumeroPedido)
{
return;
}
this._t012NumeroPedido = value;
this.OnPropertyChanged();
}
}
[BackingField(nameof(_t012PedidoItem))]
public ObservableCollection<T012_Pedido_Item> T012_Pedido_Item
{
get => this.LazyLoader.Load(this, ref this._t012PedidoItem);
set => this._t012PedidoItem = value;
}
}
public class T012_Pedido_Item
{
[Required]
[BackingField(nameof(_t012Pedido))]
public virtual T012_Pedido T012_Pedido
{
get => this.LazyLoader.Load(this, ref this._t012Pedido);
set
{
if (this._t012Pedido == value)
{
return;
}
this._t012Pedido = value;
this.OnPropertyChanged();
}
}
public decimal T012_PesoLiquido
{
get => this._t012PesoLiquido;
set
{
this._t012PesoLiquido = value;
this.OnPropertyChanged();
}
}
}
如果我尝试访问 T012_Pedido_Item 类的属性 T012_PesoLiquido 中的属性 T012_Pedido,我会收到以下错误:
System.InvalidOperationException:为警告“Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning”生成错误:尝试在“T012_Pedido_Item”类型的分离实体上延迟加载导航“T012_Pedido”。分离实体或使用“AsNoTracking”加载的实体不支持延迟加载。可以通过将事件 ID 'CoreEventId.DetachedLazyLoadingWarning' 传递给 'DbContext.OnConfiguring' 或 'A' 中的 'ConfigureWarnings' 方法来抑制或记录此异常 ddDbContext'。
如果我没有任何代码访问模型内的属性,并尝试在其他代码块中访问,一切正常。 我认为当我尝试访问属性 T012_PesoLiquido 内部时,延迟加载尚未准备好,这就是我收到错误的原因。 我想知道在这种情况下该怎么做。
提前致谢。
编辑:
我发现如果我尝试访问字段而不是属性,则不会发生错误并且我能够访问所有数据。
【问题讨论】:
标签: c# entity-framework-core ef-core-6.0