Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8195989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T05:19:36+00:00 2026-06-07T05:19:36+00:00

Currently, this is how I am handling data within my MVC 3 application. Being

  • 0

Currently, this is how I am handling data within my MVC 3 application. Being pretty new to both MVC 3 and the Entity Framework I am not quite sure this is the best approach to handling data within the application. In fact, the call to check UserExists below sometimes gives a SQLConnectionTimeout issue which seems to be completely random. I’ve tried tracing the problem through SQL profiler and it appears that the timeout occurs right after the connection is being made from EF -> SQL.

I thought I had this solved in another question here on SO but it popped back up, so I wanted to get everyone’s opinion on whether or not below is the best way to attempt data handling in my application or is there a better way that may solve the timeout issue.

Here is a link to the other article if it helps: MVC 3/EF/SQL Server strange connection timeout issue

So to summarize my question(s):

  • Is the code below acceptable?
  • Should it work fine?
  • Is there a better way?
  • Will unnecessary connections to SQL remain open from EF? (SQL Profiler makes it look like it stays open a while even after the using statement has exited)
  • Any idea on the timeout issue I posted in my other article?

Note: The repository implements IDisposable and has the dispose method listed below. It creates a new instance of the entity context in the repository constructor.

Controller (LogOn using Custom Membership Provider):

if (MembershipService.ValidateUser(model.UserName, model.Password))
{
    User newUser = new User();                    

    using (AccountRepository repo = new AccountRepository())
    {
         newUser = repo.GetUser(model.UserName);
         ...
    }
}

Membership Provider ValidateUser:

public override bool ValidateUser(string username, string password)
{
    using (AccountRepository repo = new AccountRepository())
    {
        try
        {
            if (string.IsNullOrEmpty(password.Trim()) || string.IsNullOrEmpty(username.Trim()))
                return false;

            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5");

            bool exists = false;

            exists = repo.UserExists(username, hash);

            return exists;
        }catch{
            return false;
        }
    }
}

Account Repository Methods for GetUser & UserExists:

Get User:

public User GetUser(string userName)
    {
        try
        {
            return entities.Users.SingleOrDefault(user => user.UserName == userName);
        }
        catch (Exception Ex)
        {
            throw new Exception("An error occurred: " + Ex.Message);
        }           
    }

User Exists:

 public bool UserExists(string userName, string userPassword)
 {
        if (userName == "" || userPassword == "")
            throw new ArgumentException(InvalidUsernamePassword);

        try
        {
            bool exists = (entities.Users.SingleOrDefault(u => u.UserName == userName && u.Password == userPassword) != null);
            return exists;
        }
        catch (Exception Ex)
        {
            throw new Exception("An error occurred: " + Ex.Message);
        } 
    }

Repository Snippets (Constructor, Dispose etc):

    public class AccountRepository : IDisposable
    {
         private DbContext entities;

         public AccountRepository()
         {
            entities = new DbContext();
         }

         ...

         public void Dispose()
         {
            entities.Dispose();
         }
    }

Thanks everyone – I realize that this question crit’s you for over 9000 with a giant wall of text!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T05:19:38+00:00Added an answer on June 7, 2026 at 5:19 am

    We generally follow the pattern of controlling the instantiation and disposal of the context using an IActionFilter and providing a mechanism to inject that into dependent classes (using Ninject).

    If you’re not using dependency injection / IoC you can get away with a base controller a little like the following:

    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Transactions;
    using System.Web.Mvc;
    
    public class ControllerBase : Controller
    {
        private ContextState contextState;
    
        protected EntityContext Context
        {
            get { return this.contextState.Context; }
        }
    
        protected TransactionScope TransactionScope
        {
            get { return this.contextState.TransactionScope; }
        }
    
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
    
            IsolationLevel isolationLevel = filterContext.ActionDescriptor
                .GetCustomAttributes(typeof(UnitOfWorkAttribute), false)
                .Cast<UnitOfWorkAttribute>()
                .Select(a => a.IsolationLevel)
                .DefaultIfEmpty(IsolationLevel.ReadCommitted)
                .First();
    
            Trace.TraceInformation("Creating database context & transaction scope with isolation {0}.", isolationLevel);
    
            this.contextState = new ContextState
                {
                    TransactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = isolationLevel }),
                    Context = new EntityContext()
                };
        }
    
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
    
            try
            {
                if (filterContext.Exception == null)
                {
                    Trace.TraceInformation("Commiting transaction scope.");
                    this.contextState.TransactionScope.Complete();
                }
                else
                {
                    Trace.TraceInformation("Rolling back transaction scope.");
                }
            }
            finally
            {
                try
                {
                    Trace.TraceInformation("Disposing database context.");
                    this.contextState.Context.Dispose();
                }
                catch (Exception e)
                {
                    Trace.TraceError("Failed to dispose database context. {0}", e);
                }
    
                try
                {
                    Trace.TraceInformation("Disposing transaction scope.");
                    this.contextState.TransactionScope.Dispose();
                }
                catch (Exception e)
                {
                    Trace.TraceError("Failed to dispose transaction scope. {0}", e);
                }
    
                this.contextState = null;
            }
        }
    
        private class ContextState
        {
            public EntityContext Context { get; set; }
            public TransactionScope TransactionScope { get; set; }
        }
    }
    
    /// <summary>
    /// Marks an MVC action as requiring a particular <see cref="IsolationLevel" /> when a transaction is
    /// created for it.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class UnitOfWorkAttribute : Attribute
    {
        private readonly IsolationLevel isolationLevel;
    
        public UnitOfWorkAttribute(IsolationLevel isolationLevel)
        {
            this.isolationLevel = isolationLevel;
        }
    
        /// <summary>
        /// Gets an <see cref="IsolationLevel" /> value indicating the isolation level
        /// a transaction should use.
        /// </summary>
        public IsolationLevel IsolationLevel
        {
            get
            {
                return this.isolationLevel;
            }
        }
    }
    

    Here we create an instance of your context and a transaction scope just before an action executes and then we cleanup once the action has finished up.

    In your derived controller you can then do the following…

    public class HomeController : ControllerBase
    {
        public ActionResult Index()
        {
            using (AccountRepository accountRepository = new AccountRepository(this.Context))
            {
                // do stuff
            }
    
            return View();
        }
    }
    

    Passing the context into your repository is a little messy and can be tidied up using something like Ninject to inject the dependency rather than you providing it. http://stevescodingblog.co.uk/dependency-injection-beginners-guide/ provides a pretty reasonable starting point if you’re interested.

    You can also mark up an action with the UnitOfWorkAttribute to control creation of the transaction used by the context. It’s recommended not to use implicit transaction when doing database work (http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions) so we always create a transaction scope when executing the action. This has little overhead because, unless the connection is opened, the transaction scope doesn’t do much.

    Edit: Just to answer another of your questions…

    Will unnecessary connections to SQL remain open from EF? (SQL Profiler makes it look like it stays open a while even after the using statement has exited)

    Most likely reason here is connection pooling. ADO.NET will maintain open connections for a period of time which makes subsequent calls more efficient because you don’t have the latency of opening the connection.

    Cheers,

    Dean

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

There is currently this Prototype code that does a PUT: new Ajax.Request(someUrl, { method:
I'm working within zend forms. Currently this is how it looks: I want to
I currently have this code which stores XML into an XML-type column called data,
I currently have this code: PACKETS = {}; function AddPacket(data) local id = data.ID;
I am currently handling concurrency on my page using a DateTime field. The data
This is a pretty basic scenario but I'm not finding too many helpful resources.
I have this application that relies extensively on Request.UrlReferrer for handling link clicks and
Currently this code generates a colored hyperlink to an ad listing on my site.
I need to perform an action after a jQuery .load call, currently this is
I currently have this sql statement that I wrote and it works but it's

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.