读取CSV文件并插入到LocalDB(asp.net MVC) [英] Read CSV file and insert to LocalDB (asp.net MVC)
问题描述
我正在尝试使用ASP.Net MVC进行项目,并且有一个很大的CSV文件,我想保存到LocalDB.
I'm trying out a project with ASP.Net MVC and have a large CSV file that I want to save to the LocalDB.
I have been following this tutorial (and the ones before that are about MVC): https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string
现在,我想将数据添加到已设置的该数据库中,我想从csv文件读取此数据,然后将其保存到我的数据库中.
Now I want to add data to this database that I have set up and I would like to read this data from a csv file and then save it to my database.
I have tried this: https://www.aspsnippets.com/Articles/Upload-Read-and-Display-CSV-file-Text-File-data-in-ASPNet-MVC.aspx but when I try to upload my file I get an error that my file is too large?
如果它可以自动化,我会喜欢它,这样当我启动我的应用程序时,数据库将使用csv文件中的数据填充(如果已经填充,它将不再执行此操作),或者只是某种方式编码,以便可以将csv文件中的数据添加到数据库(LocalDB).
I would love it if it could be automated so that when I start my application the database will be populated with the data from my csv file (and if it already is populated it will not do it again) or just some way of coding so that I can add the data from my csv file to the database (LocalDB).
protected override void Seed(ProductsDBContext context)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "WebbApplication.App_Data.SeedData.price_detail.csv";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
CsvReader csvReader = new CsvReader(reader);
var products = csvReader.GetRecords<PriceDetail>().ToArray();
context.PriceDetails.AddOrUpdate(c => c.PriceValueId, products);
}
}
}
推荐答案
使用 Cinchoo ETL -一个开源库,您可以使用几行代码将CSV文件批量加载到sqlserver中.
With Cinchoo ETL - an open source library, you can bulk load CSV file into sqlserver with few lines of code.
using (var p = new ChoCSVReader(** YOUR CSV FILE **)
.WithFirstLineHeader()
)
{
p.Bcp("** ConnectionString **", "** tablename **");
}
有关更多信息,请访问codeproject文章.
For more information, please visit codeproject article.
希望有帮助.
这篇关于读取CSV文件并插入到LocalDB(asp.net MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!