我正在为Asp.net Core 2.2 MVC EF应用程序使用CsvHelper。上传csv逗号分隔文件后,我可以读取数据并将其插入数据库。但是,如果csv文件内部有很多行,则即使csv内部有10行,它也只会插入第一行。以下是我的控制器代码: 我希望你能帮助我。 TIA。
[HttpPost("textCsv")]
public async Task<IActionResult> textCsv([Bind("CompanyCode,ProductCode,TransactionDate,TransactionTime,OriginatingBranch,CustomerNumber,TransactionOrigin,TypeOfPayment,CheckNumber,TransactionAmount,CustomerName,UserName,UserIP,UserDate")]BdoToDb bdoToDb, List<IFormFile> files)
{
UserDetails();
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filepath = Path.GetTempFileName();
var users = new List<BDOCsv>();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = formFile.OpenReadStream())
{
try { users = stream.CsvToList<BDOCsv>(); }
catch (Exception ex) { return BadRequest(ex.Message); }
}
}
}
int i = 0;
while (i < users.Count)
{
ViewBag.CompanyCode = users[i].CompanyCode;
ViewBag.ProductCode = users[i].ProductCode;
ViewBag.TransactionDate = users[i].TransactionDate;
ViewBag.TransactionTime = users[i].TransactionTime;
ViewBag.OriginatingBranch = users[i].OriginatingBranch;
ViewBag.CustomerNumber = users[i].CustomerNumber;
ViewBag.TransactionOrigin = users[i].TransactionOrigin;
ViewBag.TypeOfPayment = users[i].TypeOfPayment;
ViewBag.CheckNumber = users[i].CheckNumber;
ViewBag.TransactionAmount = users[i].TransactionAmount;
ViewBag.CustomerName = users[i].CustomerName;
bdoToDb.CompanyCode = ViewBag.CompanyCode;
bdoToDb.ProductCode = ViewBag.ProductCode;
bdoToDb.TransactionDate = ViewBag.TransactionDate;
bdoToDb.TransactionTime = ViewBag.TransactionTime;
bdoToDb.OriginatingBranch = ViewBag.OriginatingBranch;
bdoToDb.CustomerNumber = ViewBag.CustomerNumber;
bdoToDb.TransactionOrigin = ViewBag.TransactionOrigin;
bdoToDb.TypeOfPayment = ViewBag.TypeOfPayment;
bdoToDb.CheckNumber = ViewBag.CheckNumber;
bdoToDb.TransactionAmount = ViewBag.TransactionAmount;
bdoToDb.CustomerName = ViewBag.CustomerName;
bdoToDb.UserName = ViewBag.DisplayName;
bdoToDb.UserIP = HttpContext.Connection.RemoteIpAddress.ToString();
bdoToDb.UserDate = DateTime.Now.ToString("MM/dd/yyyy");
i++;
_context.Add(bdoToDb);
await _context.SaveChangesAsync();
}
//return View();
return RedirectToAction(nameof(Index));
}
答案 0 :(得分:0)
行
try { users = stream.CsvToList<BDOCsv>(); }
每次读取文件时都会覆盖users
列表。因此,当您这样做
while (i < users.Count)
users
列表仅包含最近读入的用户文件。
尝试将其更改为
try { users.AddRange(stream.CsvToList<BDOCsv>(); }
这会将新用户添加到现有列表中,而不是替换它们。