-
Notifications
You must be signed in to change notification settings - Fork 226
Lazy Loading
Simon Hughes edited this page Jan 16, 2020
·
8 revisions
-
In your
<database>.ttfile, setSettings.UseLazyLoading = true;
-
Make sure your connection string has
;MultipleActiveResultSets=Truein it.
-
Install NuGet package:
install-package Microsoft.EntityFrameworkCore.Proxies -
Include
UseLazyLoadingProxies();in your database context. For example:// Either in startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")) .UseLazyLoadingProxies()); ... } // Or in the database context protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=Demo;Integrated Security=True;MultipleActiveResultSets=True;"); optionsBuilder.UseLazyLoadingProxies(); } }
If you are creating a website then it's best not to use Lazy Loading as the database context is short lived (typically less than a second), can add many round-trips to the database, and you tend know up front what data you need for the view.
Prefer to .Include(p => p.Address) your related entities to load them up front in a single database call.
If you want to stay with lazy loading, that's completely fine, so long as you are aware of the extra round-trips to the database. Further reading here.
- Home
- Compared with the Microsoft scaffolder
- Connection strings
- JetBrains Rider
- Upgrading from v3 to v4
- Saving .tt does nothing
- Settings A-Z - every setting, with a page each
- Common Settings Types Explained
- Settings Callbacks
- Settings runtime values and helpers
- Filtering
- Full Control Over the Generated Code
- Enum Generation from Table Data
- Owned Entities
- JSON column support
- Global Query Filters
- Extended Property Names Feature
- Partial Properties
- File-Scoped Namespaces
- Data Annotations
- Spatial Types
- HierarchyId
- RowVersion and TimeStamp columns
- Lazy Loading
- Stored proc result sets