2012-04-13 56 views
0

我無法在Entity framwork中執行Raw Sql Where查詢。無法執行Context.Entity.SqlQuery實體框架

型號:

public partial class Web_User_Setup_Header 
{ 
    public byte[] timestamp { get; set; } 
    public string User_ID { get; set; } 
    public bool Enable { get; set; } 
    public System.DateTime Expiration_Date { get; set; } 
} 

流利的模型實體Configuraiton:

public class Web_User_Setup_HeaderConfigruation : EntityTypeConfiguration<Web_User_Setup_Header> 
{ 
    public Web_User_Setup_HeaderConfigruation() 
    { 
     ToTable("Web User Setup Header"); 
     HasKey(x => x.User_ID).Property(x => x.User_ID).HasColumnName("User ID"); 
     Property(x => x.Expiration_Date).HasColumnName("Expiration Date"); 
    } 
} 

這我執行SQL查詢:

Web_User_Setup_Header WebSetup = context.Web_User_Setup_Headers.SqlQuery("Select * from [" + Convert.ToString(HttpContext.Items["Company"]) + 
       "$Web User Setup Header] where [email protected]", uid).SingleOrDefault(); 

其中HttpContext.Items["Company"] = "Sachin Sales"

uid = "web"

當我執行上面的查詢提示錯誤爲:Invalid column name 'User_ID'.

當我在查詢更改User_ID[User ID]提示錯誤爲:

The data reader is incompatible with the specified 'JSTestWeb.Models.Web_User_Setup_Header'. A member of the type, 'User_ID', does not have a corresponding column in the data reader with the same name.

有人可以把一些關於這件事情?但是,數據庫字段名稱僅在數據庫中爲[User ID],我無法對其進行更改。

回答

0

您可以使用ESQL來構建動態查詢。但是您將需要使用ObjectContext API來執行ESQL。

public class MyContextTest : DbContext 
{ 
    public virtual ObjectContext UnderlyingObjectContext 
    { 
     get 
     { 
      return ((IObjectContextAdapter)this).ObjectContext; 
     } 
    } 
} 

查詢語法與SQL稍有不同。

Web_User_Setup_Header WebSetup = context.UnderlyingObjectContext 
    .CreateQuery<Web_User_Setup_Header>("Select VALUE C from [" +  
    Convert.ToString(HttpContext.Items["Company"]) + 
    "$Web User Setup Header] AS C where C.[User ID][email protected]", 
     new ObjectParameter("p0", uid)).SingleOrDefault(); 
+0

,所以我不能從[ 「+ Convert.ToString(HttpContext.Items [ 」公司「])+ 」 $ Web用戶設置標題]其中USER_ID = @ p0'直接做'選擇*。有什麼辦法可以讓它直接工作嗎?順便說一句,我試過你的解決方案它仍然給錯誤:(​​ – Joy 2012-04-13 07:02:28

+0

@joy什麼錯誤,你得到了嗎? – Eranga 2012-04-13 07:07:40

+0

好吧我不好,我不得不包括所有列,但它現在返回null。但是,如果50列是否存在,我必須輸入所有他們:(:(。現在多數民衆贊成什麼,我不想從一個ORM?有沒有反正我可以得到'選擇*從tablename條件='abc'' staight在那種情況下工作?:( – Joy 2012-04-13 07:08:10