开发者

C# Programmatically create ASP.NET Membership Schema

开发者 https://www.devze.com 2023-03-15 04:39 出处:网络
I was wondering what would be the best way to 开发者_如何学运维install the membership schema on the fly.

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.

How can I accomplish this? Is there a better way?


Ok I found a much better way to accomplish this, I still use the MembershipExists() function, but I install it with this statement, which I didn't know of up until a couple of minutes ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消