nhibernate where 子句中的条件 'or'
conditional 'or' in nhibernate where clause
我正在处理 nhibernate 查询,我需要 select table 中的所有记录,其中 ID 与我拥有的数组中的任何 ID 匹配。
所以我有 int[] ids
,我需要一个
.Where(x => x.id == ids[0]
|| x.id == ids[1]
|| x.id == ids[2]
等等...但数组中可以包含可变数量的 ID。这样做的正确方法是什么?
我也不确定要搜索什么,否则我可能会在 google 上找到一些东西
NHibernate 可以将 Contains 调用转换为 SQL 中的 In query。
.Where(x => ids.Contains(x.id));
您可以使用 IsIn()
:
.WhereRestrictionOn(x => x.Id).IsIn(ids);
您也可以试试:
.Where(x => Array.IndexOf(i, x.Id)>-1 );
优点:
+NHibernate 没有使用 sql - 比如 IsIn()
+比Cointains()
快3倍
在这里你找到代码来测试它
static void Main(string[] args)
{
int[] i = new[] { 1, 2, 3, 4, 5, 6, 7 };
Stopwatch stopwatch = Stopwatch.StartNew();
for (int j= 0; 1000000 > j; j++)
{
int pos = Array.IndexOf(i, 5);
if (pos > -1)
{ }
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Stopwatch stopwatch2 = Stopwatch.StartNew();
for (int j = 0; 1000000 > j; j++)
{
bool pos = i.Contains(5);
if (pos)
{ }
}
stopwatch2.Stop();
Console.WriteLine(stopwatch2.ElapsedMilliseconds);
Console.Read();
}
我正在处理 nhibernate 查询,我需要 select table 中的所有记录,其中 ID 与我拥有的数组中的任何 ID 匹配。
所以我有 int[] ids
,我需要一个
.Where(x => x.id == ids[0]
|| x.id == ids[1]
|| x.id == ids[2]
等等...但数组中可以包含可变数量的 ID。这样做的正确方法是什么?
我也不确定要搜索什么,否则我可能会在 google 上找到一些东西
NHibernate 可以将 Contains 调用转换为 SQL 中的 In query。
.Where(x => ids.Contains(x.id));
您可以使用 IsIn()
:
.WhereRestrictionOn(x => x.Id).IsIn(ids);
您也可以试试:
.Where(x => Array.IndexOf(i, x.Id)>-1 );
优点:
+NHibernate 没有使用 sql - 比如 IsIn()
+比Cointains()
在这里你找到代码来测试它
static void Main(string[] args)
{
int[] i = new[] { 1, 2, 3, 4, 5, 6, 7 };
Stopwatch stopwatch = Stopwatch.StartNew();
for (int j= 0; 1000000 > j; j++)
{
int pos = Array.IndexOf(i, 5);
if (pos > -1)
{ }
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Stopwatch stopwatch2 = Stopwatch.StartNew();
for (int j = 0; 1000000 > j; j++)
{
bool pos = i.Contains(5);
if (pos)
{ }
}
stopwatch2.Stop();
Console.WriteLine(stopwatch2.ElapsedMilliseconds);
Console.Read();
}