如何从 EF 中的 Seed() 访问 sql 文件?
How to access sql file from Seed() in EF?
我有以下内容:
string sproc = AppDomain.CurrentDomain.BaseDirectory + "/Stored Procedures/new_message.sql";
context.Database.ExecuteSqlCommand(sproc);
但是 sproc
路径由于某种原因无效。从 Seed
EF 代码优先迁移方法访问项目目录中文件的正确方法是什么?
如果这些 .sql
文件作为 嵌入资源 存储在您的程序集中,那么您可以这样做:
Assembly asy = Assembly.GetExecutingAssembly();
Stream stm = asy.GetManifestResourceStream("yourAssembly.Stored_Procedures.new_message.sql");
if (stm != null)
{
string sql = new StreamReader(stm).ReadToEnd();
// now you have the SQL statements which you can execute
context.Database.ExecuteSqlCommand(sql);
}
如果需要,您可以使用它来确定来自 Seed()
的资源的名称:
Assembly asy = Assembly.GetExecutingAssembly();
string[] names = asy.GetManifestResourceNames();
throw new Exception(string.Join("", names));
我有以下内容:
string sproc = AppDomain.CurrentDomain.BaseDirectory + "/Stored Procedures/new_message.sql";
context.Database.ExecuteSqlCommand(sproc);
但是 sproc
路径由于某种原因无效。从 Seed
EF 代码优先迁移方法访问项目目录中文件的正确方法是什么?
如果这些 .sql
文件作为 嵌入资源 存储在您的程序集中,那么您可以这样做:
Assembly asy = Assembly.GetExecutingAssembly();
Stream stm = asy.GetManifestResourceStream("yourAssembly.Stored_Procedures.new_message.sql");
if (stm != null)
{
string sql = new StreamReader(stm).ReadToEnd();
// now you have the SQL statements which you can execute
context.Database.ExecuteSqlCommand(sql);
}
如果需要,您可以使用它来确定来自 Seed()
的资源的名称:
Assembly asy = Assembly.GetExecutingAssembly();
string[] names = asy.GetManifestResourceNames();
throw new Exception(string.Join("", names));