2013-06-26 62 views
1

我想執行sql查詢。然後將檢索到的值轉儲到網頁中。我可以在c#中使用SQLCommand。但我怎麼能使用實體框架來做到這一點。我覺得困難的原因是因爲我不知道這個查詢將運行在哪個表上(至於這個,我將不得不解析select查詢)。請幫助我。使用實體框架C執行通用SQL查詢#

+1

我認爲這裏的答案可能會幫助http://stackoverflow.com/questions/915329/is-it-possible-to-run-native- SQL-與實體框架 – NDJ

回答

0

我知道已經有一個很好的答案,但我可以給你一個提示 - 你可以實現在執行大約Method模式進行無論是選擇普通的查詢,插入和更新中交易。我這樣做是這樣的:

internal class CommonDataTool 
{ 
    internal delegate object SqlCommandDelegate(); 

    /// <summary> 
    /// Use only for select where (a) return value(s) is/are expected and/or required 
    /// </summary> 
    /// <typeparam name="T"> Expected datacontext model return type, example: DataContext.User</typeparam> 
    /// <param name="context"> The DataContext (YourDataModel) instance to be used in the transaction </param> 
    /// <param name="action"> Linq to Entities action to perform</param> 
    /// <returns> Returns an object that can be implicitly casted to List of T where T is the expected return type. Example: List of DataContext.User</returns> 
    internal List <T> ExecuteSelect<T>(YourDataModel context, SqlCommandDelegate action) 
    { 
     using (context) 
     { 
      var retVal = action(); return ((ObjectQuery<T>)retVal).ToList(); 
     } 
    } 

    /// <summary> 
    /// Use for updates and inserts where no return value is expected or required 
    /// </summary> 
    /// <param name="context"> The DataContext (YourDataModel) instance to be used in the transaction </param> 
    /// <param name="action"> Linq to Entities action to perform</param> 
    internal void ExecuteInsertOrUpdate(YourDataModel context, SqlCommandDelegate action) 
    { 
     using (context) 
     { 
      using (var transaction = context.BeginTransaction()) 
      { 
       try 
       { action(); context.SaveChanges(); transaction.Commit(); } 
       catch (Exception) 
       { transaction.Rollback(); throw; } 
      } 
     } 
    } 
} 

public static class ObjectContextExtensionMethods 
{ 
    public static DbTransaction BeginTransaction(this ObjectContext context) 
    { 
     if (context.Connection.State != ConnectionState .Open) { context.Connection.Open(); } 
     return context.Connection.BeginTransaction(); 
    } 
} 

這是好事,因爲你可以然後實現與簡約LINQ查詢DataAdapter的,你可以通過爲代表的參數這樣:

var users = _dataTool.ExecuteSelect<DataContext.User>(Db, GetUsers); 

private static object GetUsers() 
{ 
    return (from u in Db.User select U).ToList(); 
} 

的另一個好處是,您的更新/插入在事務中運行,而不必在linq查詢中顯式聲明它們。

例子:

public void UpdateUser(DomainUser user) 
{ 
_dataTool.ExecuteInsertOrUpdate(Db,() => 
     { 
      Db.User.First(u => u.UserId == user.Id).Email = user.Email; 
      Db.User.First(u => u.UserId == user.Id).Name = user.Name; 
      Db.User.First(u => u.UserId == user.Id).LastName = user.LastName; 
      Db.User.First(u => u.UserId == user.Id).Password = user.Password; 
      return null; 
     });  
} 

源:http://www.marcusnordquist.com/?p=66