![](/img/trans.png)
[英]EF Core Lazy-Loading - Navigation properties fail with “The type or namespace name 'ProductProxy' does not exist in the namespace 'Castle.Proxies'”
[英]How to make lazy-loading work with EF Core 2.1.0 and proxies
我有以下型號:
public class Session
{
public int SessionID { get; set; }
public int UserID { get; set; }
public virtual User User { get; set; }
}
public class User
{
public int UserID { get; set; }
public int OrganizationID { get; set; }
public virtual ICollection<Session> Sessions { get; set; }
public virtual Organization Organization { get; set; }
}
public class Organization
{
public int OrganizationID { get; set; }
public virtual ICollection<User> Users { get; set; }
}
在DbContext
中注冊為:
modelBuilder.Entity<Session>(entity =>
{
entity.ToTable("sessions");
entity.Property(e => e.SessionID).HasColumnName("id");
entity.Property(e => e.UserID).HasColumnName("user_id");
entity.HasOne(e => e.User)
.WithMany(e => e.Sessions)
.HasForeignKey(e => e.UserID);
}
modelBuilder.Entity<User>(entity =>
{
entity.ToTable("users");
entity.Property(e => e.UserID).HasColumnName("id");
entity.Property(e => e.OrganizationID).HasColumnName("organization_id");
entity.HasOne(e => e.Organization)
.WithMany(e => e.Users)
.HasForeignKey(e => e.OrganizationID);
}
modelBuilder.Entity<Organization>(entity =>
{
entity.ToTable("organizations");
entity.Property(e => e.OrganizationID).HasColumnName("id");
}
我試圖使用延遲加載與Microsoft.EntityFrameworkCore.Proxies
描述在這里 :
builder.Register(c =>
{
var optionsBuilder = new DbContextOptionsBuilder<Context>();
optionsBuilder
.UseLazyLoadingProxies()
/* more options */
;
var opts = optionsBuilder.Options;
return new Context(opts);
}).As<DbContext>().InstancePerLifetimeScope();
我正在使用context.All<Session>
查詢會話。 但是,默認情況下, Session.User
和Session.User.Organization
為null。 要加載它們,我必須做類似context.All<Session>().Include(s => s.User).Include(s => s.User.Organization)
。 我怎么能避免這種情況? 為什么UseLazyLoadingProxies
不起作用?
2.1.300-preview2-008533
netcoreapp2.1
2.1.0-preview2-final
在Asp.net Core 2.1中使用代理配置延遲加載的步驟
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
或者在使用AddDbContext時:
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
您可以嘗試在Startup.cs
配置代理
public void ConfigureServices(IServiceCollection services)
{
#region Database configuration
// Database configuration
services.AddDbContext<DbContext>(options =>
options.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));
#endregion Database configuration
}
順便說一句,您已經可以將應用程序包更新為純2.1.0(非最終版或RC版)。 配置可能不起作用的原因之一是組件的不穩定版本。
注意: Microsoft.EntityFrameworkCore.Proxies.dll
是從nuget獨立於EFCore安裝的
我通過在服務中設置JSON序列化來解決這個問題,就像這個答案https://stackoverflow.com/a/49350457/4178475
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.