开发者

linq SingleorDefault

开发者 https://www.devze.com 2023-01-21 15:14 出处:网络
I want to return a single row from the users table开发者_如何学C using domain account id as my primary and unique key

I want to return a single row from the users table开发者_如何学C using domain account id as my primary and unique key

However when i use singleordefault and see its sql translation it performs entire select * from Users

my query is..

var user = base.SingleorDefault(t=>t.domainaccountid)

i want this to return just one row!


What is base ? Is it possible that you've coerced it to IEnumerable<T> at some point, rather than IQueryable<T>? that would cause this. Note that database composition is only possible when using IQueryable<T>, so if any of your methods have returned something other than this, composition will end.


You could try Where along with FirstOrDefault:

var user = base.Where(t => t.domainaccountid == 123).FirstOrDefault();


Try

var user = base.SingleorDefault(t=>t.domainaccountid==123);


SingleOrDefault looks for unique entries, it should be doing:

SELECT TOP 2 * FROM TABLE

It does this so that if it finds 2 results it will throw an exception as it is not unique.

If you don't care about finding it as a unique object, as you have other measure in place to prevent duplicates; or just don't care you can use FirstOrDefault in the following way:

array.FirstOrDefault(x => x.id == someOtherId);

This will perform the following:

SELECT TOP 1 * FROM TABLE

This will get your results quicker, especially in larger tables, because it will return as soon as the first result is found.

0

精彩评论

暂无评论...
验证码 换一张
取 消