c# - 在 ASP.NET Core 中也延迟加载后虚拟属性未加载

标签 c# asp.net-core .net-core asp.net-core-mvc entity-framework-core

首先,我阅读了属于该问题的所有答案,但到目前为止没有任何帮助,因此在将其标记为重复之前先阅读一次。

我创建了一个名为 ProjectMaster 的实体,它有一个名为 ClientMaster虚拟属性。 它正在加载数据,而我只在 mvc 中工作。但是现在我已经迁移到 CORE 并且这里没有加载它。 谷歌搜索后我知道要使用延迟加载来加载虚拟属性需要实现两件事。

  • 安装 Microsoft.EntityFrameworkCore.Proxies
  • 在启动时调用 ConfigureServices 中的 UseLazyLoadingProxies() 服务

我已经完成了这两个步骤以及各种备选方案。 但我仍然无法加载数据。这里我分享实体和配置服务方法。

实体:

[Table("ProjectMaster")]
public partial class ProjectMaster
{
    [Key]
    public Guid ProjectId { get; set; }

    [Required]
    [StringLength(500)]
    public string ProjectName { get; set; }

    [Required]
    [StringLength(500)]
    public string ProjectCode { get; set; }

    public Guid ClientId { get; set; }

    public Guid CreatedBy { get; set; }

    public virtual ClientMaster ClientMaster { get; set; }
}

[Table("ClientMaster")]
public partial class ClientMaster
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public ClientMaster()
    {
        ProjectMasters = new HashSet<ProjectMaster>();
    }

    [Key]
    public Guid ClientId { get; set; }

    [Required]
    [StringLength(100)]
    public string ClientName { get; set; }

    public Guid CreatedBy { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<ProjectMaster> ProjectMasters { get; set; }
}

启动:

   public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddEntityFrameworkProxies();
        services.AddDbContextPool<ApplicationDBContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("amcConn"));
            options.UseLazyLoadingProxies(true);
        });
        //services.AddDbContextPool<ApplicationDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("amcConn")));
       // services.AddDbContextPool<ApplicationDBContext>(options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("amcConn")));


        services.AddSession();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    }

Controller :

public ApiResult<List<ProjectMaster>> getallProject()
    {
        try
        {
            AMCContext _contect = new AMCContext();
            return new ApiResult<List<ProjectMaster>>
            (new ApiResultCode(ApiResultType.Success), _contect.ProjectMasters.ToList());
        }

这是我迄今为止所做的所有努力。

One thing to be notice here that this entity is present inside a class library project and all the necessary packages has been loaded in it.

如果有,请给我一些有用的建议。

最佳答案

我目前使用的版本

<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="2.2.4" />

使用下面的代码对我有用

services.AddDbContextPool<ApplicationDbContext>(options =>
 options.UseLazyLoadingProxies()
 .UseSqlServer(configuration.GetConnectionString("DefaultConnection"));

你可以去掉这行代码

services.AddEntityFrameworkProxies();

示例实体

public class Post : BaseEntity
{
    public string Title { get; set; }
    public string ShortDescription { get; set; }
    public string Content { get; set; }
    public PostStatus PostStatus { get; set; }
    public int Views { get; set; }
    public virtual User User { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Media Medias { get; set; }
}

public class Comment : BaseEntity
{
    public string Content { get; set; }
    public virtual Comment ParentComment { get; set; }
    public virtual Post Post { get; set; }
    public virtual User? User { get; set; }
    public CommentStatus CommentStatus { get; set; }
}

如果我的回答不适合你,你可以尝试使用 Include

   var comments = await _unitOfWork.Repository<Comment>().Query()
                .Include(x => x.User)
                .Include(c => c.Post)
                .Select(x => new CommentViewModel
                {
                    User = _mapper.Map<User, UserViewModel>(x.User),
                    Post = _mapper.Map<Post, PostViewModel>(x.Post),
                    Comment = _mapper.Map<Comment, CommentDto>(x),
                })
                .ToListAsync();

关于c# - 在 ASP.NET Core 中也延迟加载后虚拟属性未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203592/

相关文章:

c# - 为什么我的 UDP 多播没有到达网络上的机器?

c# - 在 Entity Framework 中尝试更新时出现错误 "A referential integrity constraint violation occurred"

c# - 收到推送通知时隐藏 Toast 通知

c# - 如何更新datagridview中的单元格?

javascript - 在 JavaScript 中转义的北欧字符

c# - Asp.Net Core SAML 响应签名验证

c# - OrchestrationRuntimeStatus 枚举序列化或反序列化

c# - 如何在.Net Core 2.2中解析Microsoft.AspNetCore.Mvc.Internal.ActionContext.GetNormalizedRouteValue

c# - .net core 2.2 windows服务完全启动后,如何配置托管服务启动?

javascript - ajax调用成功时提交表单,ajax调用失败时阻止提交