How can i change the default database for simple m

2019-02-25 10:18发布

问题:

I would like to ask this quick question about the default simple membership database that comes with asp.net mvc 4.5 internet application , my question is about where does it create its tables when I first create new user does it create its table in the default connection string (LocalDB) ? and what if I changed the default connection string to use a custom MS SQL Express database will that get reflected and those tables will be created in my new database ?

i noticed this code in the default account model and in its DbContext class it refers to default connection this was the code there :

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

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

回答1:

SimpleMembership gets initialised in the InitializeSimpleMemberhsipAttribute.cs class.

In the default MVC 4 internet project template, navigate to the Filters directory, and in the above class you'll find the initialising method:

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

That's the default setup, if you want to point it at a different database do something like this:

WebSecurity.InitializeDatabaseConnection("MyContext", "TableToPointTo", 
"UserIdColumn", "UserNameColumn", autoCreateTables: false);

In your context class:

public class MyContext : DbContext {...}

And change the name in the connection strings section inside the <configuration> section in the root web.config file:

<connectionStrings>
    <add name="MyContext" connectionString="..." />
</connectionStrings>


回答2:

I have been looking into this thread since I was facing the same issue. I had tried all the steps like -

  • Granting permission to SQLServer
  • Removing the [InitializeSimpleMembership] attribute for account controller along with adding WebSecurity.InitializeDatabaseConnection connection in Global.asax.

But nothing worked.

So tried something else -

  • Changed the Data Source in the default connection string to localhost.
  • Created an empty DB in the localhost named as MVCApp
  • Set the initial catalog in the connection string to MVCApp
  • Removed the AttachDBFilename from the connection string

So now my connection string points to a local database. And it worked.

I am still not sure why the default implementation by MS that had been working just couple of days back is not working as of now. But at this point of time I am happy with work around.