ABP框架初始化数据(自定义)

时间:2023-12-24 22:40:07

找到目录:AbpFramework.EntityFramework》Migrations》SeedData,这目录下创建类:DefaultDataCreator.cs

using System;
using System.IO;
using System.Reflection;
using VMM.Common;
using VMM.EntityFramework; namespace AbpFramework.Migrations.SeedData
{
public class DefaultDataCreator
{
private readonly TestDbContext _context; public DefaultDataCreator(TestDbContext context)
{
_context = context;
} public void Create()
{
var path1 = Utils.MapPath("/Migrations/Sql/") + "\\CreateViewCustomers.sql";//创建视图
using (StreamReader sr = new StreamReader(path1))
{
_context.Database.ExecuteSqlCommand("if exists(select * from sys.views where name='ViewCustomers') drop view ViewCustomers");//判断与删除
_context.Database.ExecuteSqlCommand(sr.ReadToEnd());//执行sql文件
}
}
}
}

助攻

/// <summary>
/// 获取物理路径
/// </summary>
/// <param name="seedFile">/floder1/floder2/</param>
/// <returns></returns>
public static string MapPath(string seedFile)
{
var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
var directoryName = Path.GetDirectoryName(absolutePath);
var path = directoryName + seedFile.Replace('/', '\\');
return path;
}

然后在AbpFramework.EntityFramework》Migrations》Configuration.cs的Seed方法中加入:new DefaultDataCreator(context).Create();一执行migration就好了。