[英]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.是否有可能从我的 Asp.net MVC (EF) 应用程序中连接到另一个数据库,运行一些脚本然后关闭连接。
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为非实体类型编写 SQL 查询
A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class.可以使用 Database 类上的 SqlQuery 方法创建返回任何类型(包括原始类型)实例的 SQL 查询。 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.即使对象是实体类型的实例,上下文也永远不会跟踪从数据库上的 SqlQuery 返回的结果。
Sending raw commands to the database将原始命令发送到数据库
Non-query commands can be sent to the database using the ExecuteSqlCommand method on Database.可以使用 Database 上的 ExecuteSqlCommand 方法将非查询命令发送到数据库。 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.请注意,在从数据库加载或重新加载实体之前,使用 ExecuteSqlCommand 对数据库中的数据所做的任何更改对上下文都是不透明的。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.