简体   繁体   English

C#以编程方式创建ASP.NET成员模式

[英]C# Programmatically create ASP.NET Membership Schema

I was wondering what would be the best way to install the membership schema on the fly. 我想知道什么是动态安装会员模式的最佳方式。

Right now the solution I'm thinking of is to somehow run aspnet_regsql.exe with arguments to execute on my db connection. 现在我正在考虑的解决方案是以某种方式运行带有参数的aspnet_regsql.exe以在我的数据库连接上执行。

How can I accomplish this? 我怎么能做到这一点? Is there a better way? 有没有更好的办法?

好的,我找到了一个更好的方法来实现这一点,我仍然使用MembershipExists()函数,但我用这个语句安装它,直到几分钟前我才知道。

SqlServices.Install(database, SqlFeatures.All, connectionString);

Did it like this: 它是这样的:

    public static void Initialize()
    {
        var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["membership"].ConnectionString);

        if (!MembershipExists(connection))
        {
            // create schema
            string regsql = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "aspnet_regsql.exe");
            string args = string.Format(@"-E -S {0} -A all -d {1}", connection.DataSource, connection.Database);

            var proc = Process.Start(regsql, args);
            if (proc != null)
                proc.WaitForExit();
        }
    }

    public static bool MembershipExists(SqlConnection connection)
    {
        try
        {
            connection.Open();
            var query = new SqlCommand("select count(*) from sysobjects where name = 'aspnet_CheckSchemaVersion' and type = 'P'", connection);
            return query.ExecuteScalar() as int? == 1;
        }
        finally
        {
            connection.Close();
        }
    }

Not sure how it'll behave on a production environment. 不确定它在生产环境中的表现如何。

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

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