2016-05-10 30 views
0

我想檢查兩個表中的用戶名可用性如何執行此操作請幫助。檢查兩個表中的用戶名可用性c#

  a = (from n in dbobj.stores 
       where n.st_UserName == storeuname 
       select n.st_id).Single(); 
      return true;   

我試圖在同一時間檢查,如:

  a = (from n in dbobj.stores && dbobj.customer 
      where n.st_UserName == storeuname or n.cu_UserName == storeuname 
       select n.st_id).Single(); 
      return true;   

幫助我,如果我在做錯誤的方式事情。

回答

0

Single假定總是返回一條記錄。根據Microsoft:

返回序列的唯一元素,並在序列中不完全包含一個元素時引發異常。

所以最好使用Any,然後適應返回語句

bool any = (from n in dbobj.stores 
      where n.st_UserName == storeuname 
      select n.st_id).Any(); 
return any; 

在你顯然是想連接兩個表的第二個查詢。你不能這樣做。相反依次執行測試

bool any = (from n in dbobj.stores 
      where n.st_UserName == storeuname 
      select n.st_id).Any(); 
if (any) { 
    return true; 
} 

any = (from n in dbobj.customer 
     where n.cu_UserName == storeuname 
     select n.st_id).Any(); 
return any; 

如果在第一個表中找不到用戶,將只查詢第二個表。

+0

可以請你告訴我,我怎麼能在數據庫 – user3757908

+0

的兩個表檢查用戶名這不回答這個問題。另外,爲什麼在Any()給你一個'bool'響應時使用Count()'? – DavidG

+0

好點。我用'Any()'替換了'Count()'。 –

1

但是你不能字面上檢查兩個表同時,但你可以在一個查詢檢查這兩個。有很多方法可以做到這一點 - 最直接的辦法就是Union兩個查詢:

a = 
    (from n in dbobj.stores 
        where n.st_UserName == storeuname 
        select n.st_id) 
    .Union 
    (from n in dbobj.stores 
        where n.cu_UserName == storeuname 
        select n.st_id) 
    .Single()