如何从 EF 中的 Seed() 访问 sql 文件?

Rob*_*ous 4 .net c# entity-framework code-first

我有以下几点:

  string sproc = AppDomain.CurrentDomain.BaseDirectory + "/Stored Procedures/new_message.sql";
  context.Database.ExecuteSqlCommand(sproc);
Run Code Online (Sandbox Code Playgroud)

但是,sproc由于某种原因,该路径无效。从SeedEF 代码优先迁移方法访问项目目录中的文件的正确方法是什么?

在此处输入图片说明

mar*_*c_s 5

如果这些.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);
}
Run Code Online (Sandbox Code Playgroud)

Seed()如果需要,您可以使用它来确定资源的名称:

Assembly asy = Assembly.GetExecutingAssembly();
string[] names = asy.GetManifestResourceNames();
throw new Exception(string.Join("", names));
Run Code Online (Sandbox Code Playgroud)