gpt4 book ai didi

entity-framework - EF Core - 如何在 Entity Framework 核心中启用延迟加载?

转载 作者:行者123 更新时间:2023-12-04 08:34:09 24 4
gpt4 key购买 nike

我已经将 Read Context 与 Write Now 分开了,默认情况下我将在 ReadOnlyContext 中启用 LazyLoading。我也用了下面的方法,可惜不行。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(@"Data Source=.;Initial Catalog=UniversityDb;Persist Security Info=True;User ID=admin;Password=asdasdsadasd");
}

我的模型:
public class Partner : BaseEntity<int>
{
public string Name { get; set; }
public DateTime CreateDate { get; set; }
public bool IsDisabled { get; set; }
public bool IsDeleted { get; set; }
public virtual ICollection<PartnerUser> PartnerUsers { get; set; }
}

我的 ef 版本:

EntityFramework core v 2.1.2


public async Task<PartnerQuery> Get(int id)
{
var result = await _partnerDbSet.SingleAsync(c => c.Id == id);
var list = result.PartnerUsers;
return new PartnerQuery()
{
CreateDate = result.CreateDate,
Name = result.Name,
Id = result.Id
};
}

我收到此错误:

"Error generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning: An attempt was made to lazy-load navigation property 'PartnerUsers' on detached entity of type 'PartnerProxy'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking()'.'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'."



如何解决这个问题?

最佳答案

您正在使用 AsNoTracking()在您的代码中的某处,使用 AsNoTracking() 时延迟加载将不起作用方法。

您有两个选择:

  • 使用 Include()加载关系的方法
  • 忽略警告并直接获取 null为您的人际关系

  • 您可以配置 EF 以忽略此错误:
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    optionsBuilder
    .UseLazyLoadingProxies()
    .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning))
    .UseSqlServer(@"Data Source=.;Initial Catalog=UniversityDb;Persist Security Info=True;User ID=admin;Password=asdasdsadasd");
    }

    关于entity-framework - EF Core - 如何在 Entity Framework 核心中启用延迟加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475560/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com