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 8777623
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T19:19:09+00:00 2026-06-13T19:19:09+00:00

Using Code First Entity Framework with .NET MVC 4 I have created a new

  • 0

Using Code First Entity Framework with .NET MVC 4 I have created a new Web Application and populated the database with object as shown below.

 public class GratifyGamingContext : DbContext
{
    public DbSet<Game> Games { get; set; }
    public DbSet<Genre> Genres { get; set; }
    public DbSet<UserProfile> UserRepository { get; set; }
}

I want to use my UserRepository table instead of the inbuilt UserContext class from AccountModel.cs for my user account access since I can’t get that the work with my existing dbContext.

    public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

My program always crashes when constructing a SimpleMembershipInitializer object from InitializeSimpleMembershipAttribute.cs. I have commented out the code I feel should be irrelevant.

    [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()
        {
            //Database.SetInitializer<UsersContext>(null);

            try
            {
                using (var context = new GratifyGamingContext())
                {
                    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);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }
    }
}

My ConnectionString is as follows:

<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-GratifyGaming-20120917185558;AttachDbFilename=|DataDirectory|\Games.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

I get the following error when calling the WebSecurity.InitializeDatabaseConnect from any AccountController page:

[SqlException (0x80131904): Directory lookup for the file
"C:\Users\Unreal\Documents\Visual Studio
2010\Projects\GratifyGaming\GratifyGaming.WebUI\App_Data\Games.mdf"
failed with the operating system error 2(failed to retrieve text for
this error. Reason: 15105). Cannot attach the file
‘C:\Users\Unreal\Documents\Visual Studio
2010\Projects\GratifyGaming\GratifyGaming.WebUI\App_Data\Games.mdf’ as
database ‘aspnet-GratifyGaming-20120917185558’.]

[TargetInvocationException: Exception has been thrown by the target of
an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType
type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0

My application is otherwise connected to the database if I do not go to any AccountController driven page.
How can I configure this application to use my UserRepository table instead of the UsersContext for user membership?

  • 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-13T19:19:10+00:00Added an answer on June 13, 2026 at 7:19 pm

    Remove the AttachDbFileName from the DefaultConnectionString in web.config

    <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-GratifyGaming-20120917185558;Integrated Security=True" providerName="System.Data.SqlClient" />
    

    Call the WebSecurity.InitialiseDatabase method in Global.asax.cs

     public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
    
            AreaRegistration.RegisterAllAreas();
            Database.SetInitializer<GratifyGamingContext>(new DatabaseInitializer()); 
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
    
            WebSecurity.InitializeDatabaseConnection(
                      connectionStringName: "DefaultConnection",
                      userTableName: "UserProfile",
                      userIdColumn: "UserID",
                      userNameColumn: "UserName",
                      autoCreateTables: true);
        }
    }
    

    Comment out [InitializeSimpleMembership] in AccountController.cs

     [Authorize]
        //[InitializeSimpleMembership]
        public class AccountController : Controller
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an ASP.NET MVC 3 application using an Entity Framework (4.3.1) Code First
So, I am using ASP.NET MVC 3 and Entity Framework 4.1 (code-first). I have
I am using Entity Framework code first and ASP.NET MVC 3. I have the
I am creating a new database model using Entity Framework 4.3 Code-FIrst; using Fluent
First some brief background: I have an existing ASP.NET MVC 1 application using Entity
I am currently using ASP.NET MVC and Entity Framework Code First using the repository
I am using Entity Framework 5 code first and ASP.NET MVC 3 . I
I'm building an ASP.NET MVC 3 site using the code-first Entity Framework 4 approach.
I am using Entity Framework 4.1 code first and ASP.NET MVC 3 and I
I'm using Entity Framework 4 Code First in my .net MVC 2.0 project and

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.