我知道延迟加载和急切加载,这意味着 ADO.NET 在需要数据之前不会连接到数据库,因此当我调用 .ToList() 或 LINQ 查询上的迭代时,它会连接并检索数据。
EF 中的 Db Context 只知道数据库的模式,让我能够将 db 作为对象和 LINQ 工作,或者知道模式并且我的记录实际上在我的内存中?
我认为我把所有记录都放在内存中是不合理的,甚至是不可能的!
另一个问题是DbContext 对内存或服务器的过载有多大?这意味着只有一个 DbContext 就足够了,或者一个 dbContext 内存过载,需要拆分它。这是 DDD 和拆分 DbContext 之间的关系。
你能给我一个链接来理解吗?
public class Db : IdentityDbContext<User>
{
//content
public DbSet<UrlEntity> ContentUrls { get; set; }
public DbSet<Content> Contents { get; set; }
public DbSet<Banner> Banners { get; set; }
//item
public DbSet<ItemCat> ItemCats { get; set; }
public DbSet<Item> Items { get; set; }
public DbSet<ItemImage> ItemImages { get; set; }
// lots of other
}
最佳答案
DbContext 是 Schema 和 Cache。并且它会跟踪之前加载的对象的对象状态,并且它会随着时间的推移而变慢。我个人发现在有限的时间内使用 DbContext 是一件好事,例如工作单元或请求-响应。
参见:
还有其他原因,尤其是在错误处理方面,为什么保持相同的上下文会导致意外行为:
Here are some general guidelines when deciding on the lifetime of the context:
When working with long-running context consider the following:
- As you load more objects and their references into memory, the memory consumption of the context may increase rapidly. This may cause performance issues.
- Remember to dispose of the context when it is no longer required.
- If an exception causes the context to be in an unrecoverable state, the whole application may terminate.
- The chances of running into concurrency-related issues increase as the gap between the time when the data is queried and updated grows.
- When working with Web applications, use a context instance per request.
- When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides.
参见:
关于c# - DbContext 只是我的数据库在内存中的架构或架构和记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24675477/