Basic LinqToSql question: Why won't this compi

2019-06-27 04:26发布

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.

9条回答
ら.Afraid
2楼-- · 2019-06-27 04:46

One of the potentially confusing things about "var" is that its type is determined at compile time, so you can't assign a range of different types to it. People with experience of dynamic languages, like Python, sometimes get confused by this, at first.

查看更多
劫难
3楼-- · 2019-06-27 04:48

change to this

var territories = db.Territories;

to

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

The reasoning is that by calling db.Territories, you are getting all the data back, returning it in a linq.table object. Db.Territores.where(... will return an IQueryable object instead.

查看更多
放我归山
4楼-- · 2019-06-27 04:51

For this type of cumulative Where, you need to tell the compiler to use IQueryable<T>:

IQueryable<Territory> territories = db.Territories;
if (someCondition)
    territories = territories.Where(t => t.PendingUserCount > 0);
... etc
查看更多
SAY GOODBYE
5楼-- · 2019-06-27 04:52

Alternative:

var territories = db.Territories.AsQueryable();
if (someCondition)
    territories = territories.Where(t => t.PendingUserCount > 0);
查看更多
戒情不戒烟
6楼-- · 2019-06-27 04:53

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.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-06-27 05:01

Your var territories is typed as a System.Data.Linq.Table<Territory> initially and then you are trying to assign the results of a Where clause (which is of type System.Linq.IQueryable<Territory>) to it.

Remember that the compiler infers the type of a var at assignment so once it is assigned the type cannot be changed.

Try something like this:

System.Linq.IQueryable<Territory> territories;
if (someCondition)
    territories = db.Territories.Where(t => t.PendingUserCount > 0);
查看更多
登录 后发表回答