【发布时间】:2019-06-10 15:25:49
【问题描述】:
我想做一个通用方法将数据导入我的应用程序。
例如,假设我有:
private static async Task<int> ImportAccount(string filename)
{
var totalRecords = await GetLineCount(filename);
var ctx = new AccountContext();
var count = 0;
var records = 0;
using (var stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
var data = line.Split('\t');
var acc = new Account(data);
await ctx.Accounts.AddAsync(acc);
// need this to avoid using all the memory
// maybe there is a smarter or beter way to do it
// with 10k it uses about 500mb memory,
// files have million rows+
if (count % 10000 == 1)
{
records += result = await ctx.SaveChangesAsync();
if (result > 0)
{
ctx.Dispose();
ctx = new AccountContext();
}
}
count++;
}
}
}
await ctx.SaveChangesAsync();
ctx.Dispose();
return records;
}
在上面的示例中,我将数据从制表符分隔文件导入到 Accounts db。
然后我需要导入属性、土地和许多其他数据库。
不必像上面那样为每个数据库创建一个方法,我想做一些类似的东西:
internal static readonly Dictionary<string, ??> FilesToImport = new Dictionary<string, ??>
{
{ "fullpath to file", ?? would be what I need to pass to T }
... more files ...
};
private static async Task<int> Import<T>(string filename)
其中 T 是有问题的数据库。
我所有的类都有一个共同点,它们都有一个使用string[] data 的构造函数。
但我不知道如何制作我能够接受的方法:
private static async Task<int> Import<T>(string filename)
然后可以做一个:
var item = new T(data);
await ctx.Set<T>().AddAsync(item);
如果我没记错的话,我将无法用参数实例化 T。
我如何制作这个通用的 Import 方法,是否可以实现?
【问题讨论】: