Jan Molbech
Jan Molbech

Reputation: 65

Linq query returns null. Can't figure out why

My result returns null.

IEnumerable<DataRow> result = ( from r in db.vedhaeftedeFilers.AsEnumerable() where r.beskedId == id select new { r.filnavn, r.filtype, r.data })as IEnumerable<DataRow>;

there are data in the database, and the id are correct. I am guessing that it has something to do with my use of IEnumerable, but cant figure out what the problem is.

Upvotes: 0

Views: 1540

Answers (3)

oscilatingcretin
oscilatingcretin

Reputation: 10959

When you do this:

select new { r.filnavn, r.filtype, r.data }

...you are returning a collection of an anonymous type. This is a problem because you're trying to cast this collection to IEnumerable<DataRow>. Since you're using as to cast, it's "dying silently" and returning null since casting with the as keyword doesn't throw an InvalidCastException if the cast fails (as opposed to casting with parethesis like MyClass x = (MyClass)MyObj).

Try this instead:

var result = ( from r in db.vedhaeftedeFilers.AsEnumerable() where r.beskedId == id select new { r.filnavn, r.filtype, r.data });

Notice I used var and didn't attempt to cast the result to a type.

Upvotes: 0

Richard
Richard

Reputation: 109160

select new { r.filnavn, r.filtype, r.data }

That creates an anonymous type with read only properties filnavn, filtype and data. Thus the type of the LINQ comprehension expression (from ... select) is IEnumerable<anonymous>.

This type does not implement IEnumerable<DataRow>, so as Jon notes, it will return null.

Upvotes: 0

Jon
Jon

Reputation: 437764

The as operator will return null if the object you are passing is not actually an IEnumerable<DataRow>, which it obviously is not because you are projecting into an anonymous type with select new { ... }.

As an aside, the AsEnumerable() call will ruin your performance by making your database table behave like a dumb array.

What exactly are you trying to do here?

Upvotes: 4

Related Questions