简体   繁体   English

MVC 4 SimpleMembership模型优先

[英]MVC 4 SimpleMembership Model first

I have researched for the last couple days on Stack and other coding sites and cant seem to find a fix for my problem. 最近几天,我在Stack和其他编码站点上进行了研究,似乎无法找到解决我的问题的方法。

My goal is to configure simplemembership with my own database.(yes i have done a search and none of them answer my question) 我的目标是使用我自己的数据库配置simplemembership。(是的,我已经进行了搜索,但没有一个回答我的问题)

I'm using visual studio 2013 and entity framework 4 我正在使用Visual Studio 2013和实体框架4

I used the internet application template for asp.net mvc 4, that has already built in login. 我将Internet应用程序模板用于asp.net mvc 4,该模板已经内置了登录名。

I do as everyone else on line has done and seems to work for some, but most of the time they are left with no answer at all. 我像其他人一样都在做,并且似乎在工作,但是大多数时候他们根本没有答案。

when i run my code and set the break points in the SimpleMembershipInitializer class. 当我运行代码并在SimpleMembershipInitializer类中设置断点时。 When I run it and click on register or login I step through the code and when it gets down to 当我运行它并单击“注册”或“登录”时,我逐步浏览代码,直到它进入

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

I get this error: "No user table found that has the name \\"mvcUser\\"." 我收到此错误: “未找到名称为“ mvcUser \\”的用户表。”

what I know: 我知道的:

  • I know there is a table named "mvcUser" 我知道有一个名为“ mvcUser”的表
  • I can CRUD the table and attribute in the table with in the site 我可以在网站中使用CRUD表和表中的属性

If you want screen shots or more code please let me know. 如果您需要屏幕截图或更多代码,请告诉我。

Here is something similar to what I am looking/talking about but I don't understand what is meant by number 2 and 3 in the selected answer. 类似于我正在寻找/谈论的内容,但我不明白所选答案中数字2和3的含义。

Controller 调节器

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

    private AdventureWorksEntities db = new AdventureWorksEntities();

This is at the top ^^ 这是顶部^^

    [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);
    }

Model 模型

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

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

Web.config 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 滤镜\\ 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);
            }
        }
    }

"No user table found that has the name XXXXX" means that you can't use Entity Framework connection string ( EntityClient provider) to initialize database connection for SimpleMembershipProvider , it must be initialized with a plain SqlClient provider connection string. “未找到名称为XXXXX的用户表”意味着您不能使用Entity Framework连接字符串( EntityClient提供程序)来初始化SimpleMembershipProvider数据库连接,必须使用简单的SqlClient提供程序连接字符串来初始化它。

There are 2 solutions to solve this problem: 有两种解决方案可以解决此问题:

Single Connection String (EDM Only) 单个连接字符串(仅EDM)

Use EntityConnectionStringBuilder instance to generate SqlClient provider connection string, then point InitializeDatabaseConnection to use generated connection string: 使用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);
    }
}

Dual Connection String 双连接线

Add a new element on connectionStrings part in web.config file which includes SqlClient provider, so that it will looks like this (one for SQL Server & another one for EF): 在包含SqlClient提供程序的web.config文件的connectionStrings部分上添加一个新元素,使其看起来像这样(一个用于SQL Server,另一个用于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>

Then, set InitializeDatabaseConnection to use newly created connection string: 然后,将InitializeDatabaseConnection设置为使用新创建的连接字符串:

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

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

NB: The accepted answer from this post mentions how to convert Code First to Model First with SimpleMembershipProvider , but here you have Model First setup from start. 注意: 这篇文章接受的答案提到了如何使用SimpleMembershipProvider将Code First转换为Model First,但是这里从一开始就具有Model First设置。

Related issues: 相关问题:

Can SimpleMembership and Entity Framework share a connection string? SimpleMembership和Entity Framework可以共享一个连接字符串吗?

Setup a valid connection string for SimpleMembership 为SimpleMembership设置有效的连接字符串

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM