简体   繁体   中英

Is it possible in Entity Framework MVC application to run .sql scripts on a different database

Is it possible that from within my Asp.net MVC (EF) application i connect to another database, run some scripts and then close the connection.

Since this application already connects to a default database as soon as i run the application. Can i then connect to another one simultaneously (from a controller action) for a while and run some scripts on that one and then close connection?

Setup a separate context with the connection string for the other database and use on of the options below.

Writing SQL queries for non-entity types

A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class. For example:

using (var context = new BloggingContext()) 
{ 
    var blogNames = context.Database.SqlQuery<string>( 
                       "SELECT Name FROM dbo.Blogs").ToList(); 
}

The results returned from SqlQuery on Database will never be tracked by the context even if the objects are instances of an entity type.

Sending raw commands to the database

Non-query commands can be sent to the database using the ExecuteSqlCommand method on Database. For example:

using (var context = new BloggingContext()) 
{ 
    context.Database.ExecuteSqlCommand( 
        "UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1"); 
}

Note that any changes made to data in the database using ExecuteSqlCommand are opaque to the context until entities are loaded or reloaded from the database.

Output Parameters

If output parameters are used, their values will not be available until the results have been read completely.

Ok. So This is what i simply did in my controller

public class AdminController : Controller
{
    public ActionResult Install()
    {
        foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)
        {


                //get all files from this folder except insert and mysql create scripts and then run each of them
                string script = System.IO.File.ReadAllText(@"C:\Test.sql");
                MySqlConnection conn = new MySqlConnection(c.ConnectionString);
                try
                {
                    conn.Open();
                    MySqlScript m = new MySqlScript(conn, script);
                    m.Delimiter = "$$";
                    m.Execute();
                    conn.Close();
                }
                catch { }

        }

        return View();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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