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条回答
迷人小祖宗
2楼-- · 2019-06-27 05:04

You need to use the IQueryable tyupe as others have suggested:

also this linq query maybe also work:

var query = from territories in db.Territories
            where territories.SomeProperty == SomeCondition
            where territories.PendingUserCount > 0
            select territories;
查看更多
对你真心纯属浪费
3楼-- · 2019-06-27 05:07

Because you've typed "var" as a Table<Territory> and then try to reassign it as a IQueryable<Territory>.

This is equivalent to saying

  var i = 0

  i = "a string";

EDIT: To clarify, var is implicitly strong typed at compile time not run time, unlike dynamically typed scripting language.

查看更多
成全新的幸福
4楼-- · 2019-06-27 05:08

You can't re-assign a var to a different type after you've declared it. So your var declaration has already typed it to System.Data.Linq.Table.

It's a fire once thing.

查看更多
登录 后发表回答