I'm using LinqToExcel along with C# to read data from a MS Excel spreadsheet and then update data records in my MS SQL database.
The Excel file has these headers: COURSE_ID, PROVIDER_COURSE_TITLE
My code is like this:
public class TestDataCourse
{
[ExcelColumn("PROVIDER_COURSE_TITLE")]
public string cTitle
{
get;
set;
}
}
///////////////////////////////
string pathToExcelFile = @"C:\\O_COURSES.xlsx";
ConnexionExcel ConxObject = new ConnexionExcel(pathToExcelFile);
//read data from excel
var query1 = (from a in ConxObject.UrlConnexion.Worksheet<TestDataCourse>("O_COURSES")
select a).Take(2000).ToList();
//Get data from MS SQL database that need updated
var courses = _courseService.GetAllCoursesFromDB().Take(100).ToList();
int count = 0;
foreach (var course in courses)
{
//Iterate through the excel doc and assign the
TestDataCourse fakeData = query1.Skip(count).Take(1).FirstOrDefault();
course.CourseTitle = fakeData.cTitle;
count++;
}
_courseService.Save();
When I run this code I can see that it does update some of the records in my database, but as the code execution continues, I get a Source Not Available tab open within my Visual Studio and a Cannot perform runtime binding on a null reference.
The null reference exception had me thinking that maybe there was some null data in the Excel doc, so I put this line of code into my for loop:
course.CourseTitle = fakeData == null ? "Course Test" : fakeData.cTitle;
But I still get the same problem.
Could anyone please help?
Thanks.