4

I'm using the following code to query an excel file in LinqToExcel:

var excelFile = new LinqToExcel.ExcelQueryFactory(@"\"+txtFileName.Text.Replace(@"\\",@"\"));

var properties = from p in excelFile.Worksheet<Property>()
                 where AssessmentID != null
                 select p;
foreach (var autoP in properties)
        doSomething();

When I look at the runtime debugger, I see an "InvalidCastException" while looking at the "Results View" of the properties variable. So, I'm assuming that there's something funky going on with my class definition. I'm also assuming that I don't need to map all members of the class to the excel file, but rather only the ones I see fit.
So, Here's the class definition as well:

public class Property
{

    [DataMember]
    public int? Year { get; set; }

    [DataMember]
    public string ChangeReason { get; set; }

    [DataMember]
    public string AssessmentID { get; set; }

    [DataMember]
    public string CallBackNotes { get; set; }

    [DataMember]
    public string InspectionNotes { get; set; } 

    [DataMember]
    public string Notes { get; set; }

    [DataMember]
    public bool Authorization { get; set; }

    [DataMember]
    public string ChargeStatus { get; set; }

    [DataMember]
    public string LegalLandDesc { get; set; }

    [DataMember]
    public string Address { get; set; }
    }

Here's a link to the source code for linqToExcel on GitHub:LinqToExcel The generics are more complicated than I've seen, and are something that I (apparently) need to brush up on.

Is there something glaring that I'm missing that would cause this issue? Any ideas as to where to look or what to do to resolve these errors?

Rolan
  • 2,924
  • 7
  • 34
  • 46

1 Answers1

11

The where clause of the query is what was causing the error. It was referencing the null keyword which was not applicable in the context. I changed it to:

where  !String.IsNullOrEmpty(p.AssessmentID) 

This solved my issue.

Note to self: When inheriting code from others, check the basics first!

Rolan
  • 2,924
  • 7
  • 34
  • 46
  • 1
    OMG, your post saved me some grief here. I revisited an old project today where an != null where clause was originally working fine and had been for a few years, but suddenly today started throwing this same error. – Ho Ho Ho Oct 06 '16 at 18:01
  • 1
    Thanks, you saved my life. – Billy Jake O'Connor Oct 31 '16 at 10:58
  • 2
    @Rolan - You have identified my exact issue and your fix works but could you explain why `null` is "not applicable in the context"? This issue doesn't seem to be manifest in LinqPad. – Peter Wone Jan 31 '17 at 01:54
  • Thanks tons for this, same issue as others mentioned. Revisited code that was working no problem and exception was thrown now. – knightscharge Dec 04 '19 at 15:54