插入.CSV 到 AspNetUsers 中使用 .NET Core MVC 3.0



所以基本上我正在尝试从客户端获取上传的.csv文件并将其插入到Dbo.AspNetUsers中。 我已经为从.csv获得的三个字段定义了以下文件

public class CsvStudent : IdentityUser
{
public string Name { get; set; }
public int Number { get; set; }
public string Course { get; set; }
}

这是从客户端上传.csv的代码。

<form class="col-xs-12" method="post" asp-controller="User" asp-action="ImportUsers" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="file" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>

这是到目前为止应该获取上传.csv的控制器。

public async Task<IActionResult> ImportUsers(IFormFile file)
{
var data = new MemoryStream();
file.CopyTo(data);
TextReader reader = new StreamReader(data);
var csvReader = new CsvReader(reader);
var records = csvReader.GetRecords<User>();

我什至不确定上面的代码是否正确读取了.csv,但基本上我想在这里做什么,正如我在第一段中解释的那样, 是将记录上传到 DBO。AspNetUsers 表,我不确定该怎么做。 提前感谢!

您可以参考以下演示:

1.模型和应用数据库上下文:

public class CsvStudent : IdentityUser
{
public string Name { get; set; }
public int Number { get; set; }
public string Course { get; set; }
[NotMapped]
public string Password { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<CsvStudent>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}

2.CSV文件 :

Name,Number,Course,Password
Sherry,6,Chinese,Sherry123#
Daniel,2,Math,Daniel456#

3.控制器:

public async Task<IActionResult> ImportUsers(IFormFile file)
{
var data = new MemoryStream();
await file.CopyToAsync(data);
data.Position = 0;
TextReader reader = new StreamReader(data);
var csvReader = new CsvReader(reader ,new CsvHelper.Configuration.Configuration
{
HasHeaderRecord = true, //Gets or sets a value indicating if the CSV file has a header record. Default is true.
HeaderValidated = null,//Gets or sets the function that is called when a header validation check is ran
MissingFieldFound=null //Gets or sets the function that is called when a missing field is found.
});
var records = csvReader.GetRecords<CsvStudent>().ToList();
foreach (var item in records)
{
//check if the user has been existing in db 
var user = await _userManager.FindByNameAsync(item.Name);
if (user == null)
{
user = new CsvStudent
{
Name = item.Name,
Number = item.Number,
Course = item.Course,
UserName = item.Name
};
await _userManager.CreateAsync(user, item.Password);
}
}
return Json(records);
}

有关 CsvHelper.Configuration 的更多详细信息,您可以参考此处。

相关内容

  • 没有找到相关文章

最新更新