I have an ASP.NET MVC 5 project and I want to fill a certain table in the database with information from a .tsv file.
These are what the first 3 lines of the file look like:
CAE_Num CAE_Description
01111 Description 1
01112 Description 2
So I made a model/class that looks like this:
namespace project.Models
{
public class CAE
{
public int Id { get; set; } // id
public int CAE_Num { get; set; }
public string CAE_Description { get; set; }
public static CAE FromTsv(string tsvLine)
{
string[] values = tsvLine.Split('\t');
CAE cae = new CAE();
cae.CAE_Num = Convert.ToInt32(values[0]);
cae.CAE_Description = Convert.ToString(values[1]);
return cae;
}
}
}
The model includes a function that splits a string and creates a CAE object based on it.
In order to fill the database before runtime, I decided to use the Seed method in the Configuration class, created when you enable database migrations. I've used this in a different project before, for user roles, so I know this is one of the right places I can achieve what I want. So here's what I did:
namespace project.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using project.Models;
using System.IO;
using System.Collections.Generic;
using System.Web;
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ApplicationDbContext context)
{
List<CAE> listCAEs = File.ReadAllLines(HttpContext.Current.Server.MapPath("~/App_Data/CAE.tsv")) // reads all lines into a string array
.Skip(1) // skip header line
.Select(f => CAE.FromTsv(f)) // uses Linq to select each line and create a new Cae instance using the FromTsv method.
.ToList(); // converts to type List
listCAEs.ForEach(s => context.CAEs.Add(s));
context.SaveChanges();
}
}
}
When I run update-database
I get the error/warning:
Object reference not set to an instance of an object.
and my model isn't filled at all when I go to localhost:xxxx/CAEs
, nor is any information added to the dbo.CAEs [Data]
table in the Server Explorer.
I am wondering if my issue is with the path to the .tsv file. I googled and I read that having the file in the App_Data folder saves me the trouble of hardcoding a file path.