在Database-First ASP.NET MVC4项目中使用SimpleMembershipProvider和我自己的数据库

时间:2014-07-16 04:23:23

标签: c# asp.net asp.net-mvc-4 simplemembership ef-database-first

我有一个数据库优先的ASP.NET MVC 4项目,并希望将SimpleMembershipProvider与我的数据库中的自定义user_info表一起使用。我正在使用Entitiy Framework 6和SQL Server。我已经在互联网上寻找解决方案,但没有运气。

我的user_info表如下所示:

[Id]            INT            IDENTITY (1, 1) NOT NULL,
[email]         NVARCHAR (MAX) NULL,
[first_name]    NVARCHAR (MAX) NULL,
[last_name]     NVARCHAR (MAX) NULL,
[internal_role] INT            NULL,
CONSTRAINT [PK_user_info] PRIMARY KEY CLUSTERED ([Id] ASC)

我试图按照以下步骤操作 How can I customize simple membership provider to work with my own database ASP.NET mvc 4,但我不认为此方法适用于非Code-First项目。我收到服务器错误"无法找到请求的.Net Framework数据提供程序。它可能没有安装。"当我尝试将以下代码添加到函数SimpleMembershipInitializer()时。

WebSecurity.InitializeDatabaseConnection("ReservationSystemEntities", "user_info", "Id", "email", autoCreateTables: true);

以下是我的Web.config文件中的相关信息:

<configSections>
  <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxxxx" requirePermission="false" />
</configSections>

<connectionStrings>
<add name="ReservationSystemEntities" connectionString="metadata=res://*/ReservationSystem.csdl|res://*/ReservationSystem.ssdl|res://*/ReservationSystem.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\v11.0;initial catalog=ReservationSystem;integrated security=True;user id=xxxxx;password=xxxxx;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  </providers>
</entityFramework>

根据这个答案,我甚至不确定这是否可行:SimpleMembershipInitializer won't initialize

根据这个答案Using MVC 4 SimpleMembership with an existing database-first EF model,我需要指定一个像这样的连接字符串:

<add name="CONNECTION_STRING_NAME" connectionString="data source=SERVER;initial catalog=DATABASE;user id=USER;password=PASSWORD;" providerName="System.Data.SqlClient" />

我不知道如何将我的连接字符串转换为这样的连接字符串。这种类型的连接字符串只有在使用Code-First时才有效吗?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我终于找到了答案!有关原始问题/答案,请参阅Using SimpleMembership with EF model-first

SimpleMembership可以首先使用模型/数据库。这是解决方案:

来自MVC 4 Internet Application模板的

1。InitializeSimpleMembershipAttribute.cs应如下所示

namespace WebAndAPILayer.Filters
{
    [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()
            {
                try
                {
                    WebSecurity.InitializeDatabaseConnection("ConnStringForWebSecurity", "UserProfile", "Id", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Something is wrong", ex);
                }
            }
        }
    }
}

2.删除AcountModel.cs

中的CodeFirst类

3.Fix AccountCotroler.cs使用您的模型优先DbContext(ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)方法)

4.定义您的"ConnStringForWebSecurity"连接字符串,该字符串与用于模型优先的数据库访问的那个时髦conn字符串不同,请注意我们使用提供程序System.Data.SqlClient而不是System.Data.EntityClient

 <connectionStrings>
         <add name="ModelFirstEntityFramework" connectionString="metadata=res://*/Context.csdl|res://*/Context.ssdl|res://*/Context.msl;provider=System.Data.SqlClient;provider
 connection string=&quot;data source=.\SQLEXPRESS;Initial
 Catalog=aspnet-MVC4;Integrated
 Security=SSPI;multipleactiveresultsets=True;App=EntityFramework&quot;"
 providerName="System.Data.EntityClient" />
         <add name="ConnStringForWebSecurity" connectionString="data source=.\SQLEXPRESS;Initial Catalog=aspnet-MVC4;Integrated
 Security=SSPI" providerName="System.Data.SqlClient" />
       </connectionStrings>