I am trying to get the results of a linq query int a file. I created and array of the same type as the FileHelpers class I created, then queried the data and assigned the values to the array I just created.
I get the following error:
Object reference not set to an instance of an object.
The strange thing is that the item giving out the error is the one that is getting a value assigned to it. Not sure why this is happening:
NorthwindEntities dbContext = new NorthwindEntities();
var q = from d in dbContext.Products
select d;
producdt[] items = new producdt[q.Count()];
for (int i = 0; i < q .Count(); i++)
{
items[i].Field1 = q.ToList()[i].ProductName;
}
FileHelperEngine<producdt> engine = new FileHelperEngine<producdt>();
engine.WriteFile("test.text", items);
including product class:
[FixedLengthRecord(FixedMode.ExactLength)]
public sealed class producdt
{
[FieldFixedLength(10)]
public String Field1;
[FieldFixedLength(10)]
public String Field2;
[FieldFixedLength(10)]
public String Field3;
[FieldFixedLength(10)]
public String Field4;
[FieldFixedLength(10)]
public String Field5;
}
You must initialize items[i]
before using it in the for
loop. The problem is that you have created the array, but its individual elements are null
. I guess you'd want to assign the return of your linq query to this array, after doing some projection using Select()
.
Though I don't know the specifics of your class, I suppose you'd do it on the following lines:
producdt[] items = (from d in dbContext.Products
select new producdt(){
Field1 = d.Field1,
Field2 = d.Field2,
Field3 = d.Field3,
Field4 = d.Field4
}).ToArray();