Aggiornamento: questo non ha funzionato. Vedi i commenti!
Odio quando cerco StackOverflow e la risposta è: "Non puoi!" oppure "Potresti, ma solo se cambi completamente ogni singola chiamata che hai mai fatto."
Riflettere qualcuno? Speravo che questa sarebbe stata un'impostazione di DbContext. Ma poiché non lo è, ne ho fatto uno usando la riflessione.
Questo pratico piccolo metodo imposterà AsNoTracking su tutte le proprietà di tipo DbSet.
private void GloballySetAsNoTracking()
{
var dbSetProperties = GetType().GetProperties();
foreach (PropertyInfo pi in dbSetProperties)
{
var obj = pi.GetValue(this, null);
if (obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(DbSet<>))
{
var mi = obj.GetType().GetMethod("AsNoTracking");
mi.Invoke(obj, null);
}
}
}
Aggiungerlo a un costruttore DbContext sovraccarico.
public ActivationDbContext(bool proxyCreationEnabled, bool lazyLoadingEnabled = true, bool asNoTracking = true)
{
Configuration.ProxyCreationEnabled = proxyCreationEnabled;
Configuration.LazyLoadingEnabled = lazyLoadingEnabled;
if (asNoTracking)
GloballySetAsNoTracking();
}
Usa la riflessione, il che significa che qualcuno commenterà rapidamente che si tratta di un successo in termini di prestazioni. Ma è davvero tanto un successo? Dipende dal tuo caso d'uso.
il tuo link mostrami l'errore –
@AliYousefie grazie, l'ho risolto. –