[英]Permanently disable Configuration.ProxyCreationEnabled in EF?
[英]What is the equivalent of .Configuration.ProxyCreationEnabled in EF Core?
Entity Framework Core 中 .Configuration 的等價物是什么? 接收錯誤如下
代碼示例:
List<DocumentStatus> documentStatuses;
using (var db = new ModelDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
documentStatuses = db.DocumentStatus.ToList();
}
using (var db = new ModelDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
//Expression<Func<Owner, bool>> predicate = query => true;
db.Configuration.ProxyCreationEnabled
整個錯誤信息:
錯誤 CS1061“ModelDBContext”不包含“Configuration”的定義,並且找不到接受“ModelDBContext”類型的第一個參數的可訪問擴展方法“Configuration”(您是否缺少 using 指令或程序集引用?)
基於 Entity Framework Core 文檔: https : //docs.microsoft.com/en-us/ef/core/querying/related-data ,從 EF Core 2.1 開始,有一種方法可以使用或不使用代理啟用延遲加載。
1. 使用代理延遲加載:
一種。 確保您的導航屬性被定義為“虛擬”
灣安裝 Microsoft.EntityFrameworkCore.Proxies 包
C。 通過調用 UseLazyLoadingProxies 啟用它
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
或者在使用 AddDbContext 時啟用它
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
2. 無代理延遲加載:
一種。 將 ILazyLoader 服務注入實體,如實體類型構造函數中所述。 例如:
public class Blog
{
private ICollection<Post> _posts;
public Blog()
{
}
private Blog(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
private ILazyLoader LazyLoader { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Post> Posts
{
get => LazyLoader.Load(this, ref _posts);
set => _posts = value;
}
}
默認情況下,EF Core 不會使用帶有代理的延遲加載,但如果您想使用代理,請遵循第一種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.