简体   繁体   English

MVC应用程序中设置的数据库上下文可以使用多长时间?

[英]How long will a DB context that's set in a MVC application be available for?

I have the following in my MVC Application: 我的MVC应用程序中包含以下内容:

namespace WebUx.Areas.User.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

Plus: 加:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

    private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            System.Diagnostics.Debug.Write("Set Initializer\n");
            Database.SetInitializer<UsersContext>(null);


            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

            }

I understand that when there's a call to the account controller then this will set the DB context but once this is set will it stay set for my application. 我了解到,当调用帐户控制器时,这将设置数据库上下文,但是一旦设置,它将为我的应用程序保持设置。 What about later on for other users who connect. 以后对其他连接的用户该怎么办。 Will the DB context always be available? 数据库上下文将始终可用吗?

The reason I am asking this is that I have other information that I want to store in a table and access with Web API. 我之所以这样问,是因为我还有其他信息要存储在表中并可以通过Web API访问。 Should I code in something similar for these controllers so that each time I check that there's a DB context available or could I just use this? 我是否应该为这些控制器编写类似的代码,以便每次检查是否有可用的数据库上下文时都可以使用?

The connection is tightly coupled to the DbContext . 该连接与DbContext紧密耦合。 As a result, the connection will only be open when your class which inherits DbContext , UsersContext in your case, retains its scope. 因此,仅当继承了DbContext (在您的情况下为UsersContext类保留其作用域时,连接才会打开。

In your example, UsersContext is scoped to the using block. 在您的示例中, UsersContext的作用域为using块。

using (var context = new UsersContext())
{
 //some actions
}

Therefore, once "some actions" are finished, the connection will close and any attempt to access lazy loading will throw an exception stating the connection is no longer available. 因此,一旦“一些操作”完成,该连接将关闭,并且任何访问延迟加载的尝试都将引发异常,表明该连接不再可用。 Every time you need to access your database, you should start a new connection in my opinion. 每次您需要访问数据库时,我都应该启动一个新连接。 What you want to make sure is that you only make one actual trip to the database. 您要确保的是,您只实际进行了一次数据库访问。 Make sure that your query is optimized so that you do not make multiple trips to the database instead of just doing it all at once as that will affect your performance. 确保优化查询,以免多次访问数据库而不是一次执行所有操作,因为这会影响性能。

Edit 编辑

As a side note, the using block breaks down into this: 附带说明一下,using块可细分为:

try{
 var context = new UsersContext();
 //some actions
}finally{
 context.Dispose();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mvc 5 asp两个db上下文如何允许迁移到true - mvc 5 asp two db context how to allow both migration to true 我如何在MVC3 jquery应用程序中实现长轮询 - How do I implement long polling in MVC3 jquery application 如何在MVC应用程序中使用身份设置用户角色 - How to set User Role with Identity in MVC application 单元测试ASP.NET(非MVC)-如何克服“在此上下文中请求不可用”的问题? - Unit Testing ASP.NET (not MVC) - How do I get past “Request is not Available in this context.”? .NET WebForms应用程序会话信息不适用于MVC - .NET WebForms application session information not available to MVC Asp.net MVC MiniProfiler“请求在此上下文中不可用” - Asp.net MVC MiniProfiler “Request is not available in this context” ASP.Net MVC2-设置ViewModel值,并使用DataAnnotations从数据库对象的值中检索 - ASP.Net MVC2 - Set ViewModel values with retrieved from db object's values with DataAnnotations 如何使用Dependecy注入管理n层asp.net应用程序中的数据库上下文? - How to manage db context in n-tier asp.net application with dependecy injection? 如何在MVC .NET C#应用程序的内部和外部提供C#对象 - How to have a C# object available outside and inside an MVC .NET C# application 如何将Login.aspx页设置为MVC应用程序中的默认页 - How to set Login.aspx page as the default page in an MVC Application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM