我有以下型号:
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");
}
我正在尝试使用here所述的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
答案 0 :(得分:8)
在Asp.net Core 2.1中配置代理的延迟加载的步骤
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
或者在使用AddDbContext时:
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
答案 1 :(得分:7)
您可以尝试在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
答案 2 :(得分:0)
我通过在服务中设置JSON序列化来解决此问题,例如: https://stackoverflow.com/a/49350457/4178475