如何将byte []转换为模型

时间:2018-05-02 02:21:09

标签: c# entity-framework model stream

我正在阅读此answer以使用MVC上传文件。我已经在InputStream.Read之后拥有该文件,但不知道如何使用它来创建IEnumerable<MyModel>,因此我可以使用EF将其发送到数据库。该文件是一个CSV文件,我知道。

的结构
public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    byte[] uploadedFile = new byte[model.File.InputStream.Length];
    model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

    // now you could pass the byte array to your model and store wherever 
    // you intended to store it

    return Content("Thanks for uploading the file");
}

我的模特:

public class PriceViewModel
{        
    public int PriceId { get; set; }

    public int? YearSelected { get; set; }
    public int? WeekSelected { get; set; }
    public int? StateSelected { get; set; }
}

1 个答案:

答案 0 :(得分:2)

将字节转换为字符串

var csv = Encoding.UTF8.GetString(uploadedFile);

然后将CSV解析为模型。

CsvHelper应该对此有所帮助。

var textReader = new StringReader(csv);
var helper = new CsvHelper(textReader);
IEnumerable<PriceViewModel> records = helper.GetRecords<PriceViewModel>();

从那里,您可以验证数据并保存到数据库。