MVC 4 SimpleMembership 模型优先

MVC 4 SimpleMembership Model first

过去几天我在 Stack 和其他编码网站上进行了研究,但似乎无法找到解决我的问题的方法。

我的目标是使用我自己的数据库配置简单会员。(是的,我已经进行了搜索,其中 none 回答了我的问题)

我正在使用 visual studio 2013 和 entity framework 4

我使用了 asp.net mvc 4 的 Internet 应用程序模板,它已经内置了登录。

我按照网上其他人所做的那样做,似乎对某些人有用,但大多数时候他们根本没有答案。

当我 运行 我的代码并在 SimpleMembershipInitializer class 中设置断点时。当我 运行 它并单击注册或登录时,我逐步执行代码,当它下降到

WebSecurity.InitializeDatabaseConnection("AdventureWorksEntities", "mvcUser", "userID", "userName", autoCreateTables: false);

我得到这个错误:"No user table found that has the name \"mvcUser\"."

我所知道的:

如果您需要屏幕截图或更多代码,请告诉我。

Here 与我 looking/talking 的意思类似,但我不明白所选答案中数字 2 和 3 的含义。

控制器

  [Authorize]
  [InitializeSimpleMembership]
  public class AccountController : Controller
  {

    private AdventureWorksEntities db = new AdventureWorksEntities();

这是最上面的^^

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.userName, model.UserPassword);
                WebSecurity.Login(model.userName, model.UserPassword);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

型号

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

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

Web.config

 <connectionStrings>    
 <add name="AdventureWorksEntities" connectionString="metadata=res://*/Models.AdventureworksContext.csdl|res://*/Models.AdventureworksContext.ssdl|res://*/Models.AdventureworksContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=LEMN-476W-IT;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
 </connectionStrings>

Filter\InitializerSimpleMembership.cs

private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            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("AdventureWorksEntities", "mvcUser", "userID", "userName", autoCreateTables: false);
            }
            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);
            }
        }
    }

“没有用户 table 发现名称为 XXXXX” 表示您不能使用 Entity Framework 连接字符串(EntityClient provider) 来初始化 SimpleMembershipProvider 的数据库连接,它必须使用普通的 SqlClient 提供程序连接字符串进行初始化。

解决这个问题有2种方案:

单一连接字符串(仅限 EDM)

使用EntityConnectionStringBuilder实例生成SqlClient提供商连接字符串,然后指向InitializeDatabaseConnection使用生成的连接字符串:

private class SimpleMembershipInitializer 
{
    public SimpleMembershipInitializer() 
    {
        // initializer settings here

        var connectionBuilder = new EntityConnectionStringBuilder("AdventureWorksEntities");
        string sqlConnectionString = connectionBuilder.ConnectionString;

        WebSecurity.InitializeDatabaseConnection(sqlConnectionString, "mvcUser", "userID", "userName", autoCreateTables: false);
    }
}

双连接字符串

在 web.config 文件的 connectionStrings 部分添加一个新元素,其中包括 SqlClient 提供程序,这样它看起来像这样(一个用于 SQL 服务器,另一个一个用于 EF):

<connectionStrings>
   <add name="AdventureWorksDatabase" connectionString="Data Source=LEMN-476W-IT;Initial Catalog=AdventureWorks;Integrated Security=True" providerName="System.Data.SqlClient" />
   <add name="AdventureWorksEntities" connectionString="metadata=res://*/Models.AdventureworksContext.csdl|res://*/Models.AdventureworksContext.ssdl|res://*/Models.AdventureworksContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=LEMN-476W-IT;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

然后,设置InitializeDatabaseConnection使用新创建的连接字符串:

private class SimpleMembershipInitializer 
{
    public SimpleMembershipInitializer() 
    {
        // initializer settings here

        WebSecurity.InitializeDatabaseConnection("AdventureWorksDatabase", "mvcUser", "userID", "userName", autoCreateTables: false);
    }
}

注意:this post 接受的答案提到如何使用 SimpleMembershipProvider 将代码优先转换为模型优先,但这里您从一开始就设置了模型优先。

相关问题:

Can SimpleMembership and Entity Framework share a connection string?

Setup a valid connection string for SimpleMembership