c# - DbContext 只是我的数据库在内存中的架构或架构和记录

标签 c# sql linq entity-framework

我知道延迟加载和急切加载,这意味着 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/

相关文章:

c# - 如果我使用 OWIN Startup.cs 类并将所有配置移到那里,我是否需要 Global.asax.cs 文件?

c# - WebDriver C# - 使用部分文本从下拉列表中选择一个项目

php - SQL:从数据库中获取所有缺失的日期记录

c# - 在 C# 中使用 Lambda 返回键=>值对数组

linq - 获取LINQ查询的查询语法

c# - lambda 参数如何映射到 TakeWhile 中?

c# - 我该如何修复 csharp-mode.el?

c# - 如何使用 TextMate 作为我的 IDE 在 C# 中编程?

mysql - SQLite 和其他数据库中的 Arel

sql - 我可以在应用限制后重新排序 SQL 选择吗?