Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic LinqToSql question: Why won't this compile?

Tags:

c#

linq-to-sql

I've been introducing myself to LinqToSQL lately through a poorly-made project at work. I'm curious as to why this works:

var territories = db.Territories.Where(t => t.PendingUserCount > 0);

But this results in a compilation error:

var territories = db.Territories;
if (someCondition)
    territories = territories.Where(t => t.PendingUserCount > 0);
// Cannot implicitly convert 'System.Linq.IQueryable<Territory> to System.Data.Linq.Table<Territory>

I've also tried to call db.Territories.ToList(), but to no avail.

I'm sure it's just a misunderstanding of how Linq works, but I'd be appreciative if someone could help me out.

like image 360
Matt Grande Avatar asked Nov 29 '22 00:11

Matt Grande


1 Answers

db.Territories returns a table object. Hence the 'var' will be of type System.Data.Linq.Table. Later you try (based on some condition) to assign something of type System.Linq.IQueryable to the variable. As .NET is strongly typed, the compiler throws an error.

Variables of type var will be assigned a type when they get assigned first. That's how I try to remember myself.

like image 151
Sascha Avatar answered Dec 10 '22 02:12

Sascha