2015-10-28 45 views
0

將Dapper ORM查詢的輸出獲取到提供查詢方法的類的數據成員中的最簡單方法是什麼?使用Dapper ORM的最簡單方法

這是我的代碼的方法A(醜)和B(不工作):

public class MyLab_ClientRef 
{ 
    public int UserId { get; set; } 
    public string ClientId { get; set; } 
    // ... more fields ... 

    public bool GetUser(OracleConnection conn, int UserId, string ClientId) 
    { 
     bool Ok = false; 
     IEnumerable<MyLab_ClientRef> QueryResultRecords = 
      conn.Query<MyLab_ClientRef>(@" 
       SELECT * 
       FROM MyLab_ClientRef 
       WHERE UserId = :UserId 
        AND ClientId = :ClientId", 
      new { UserId = UserId, ClientId = ClientId }); 
     if (QueryResultRecords.Count() == 1) 
     { 
      // Method A 
      MyLab_ClientRef Rec = QueryResultRecords.First(); // works 
      CopyRec(Rec, this);        // ugly 

      // Method B 
      this = QueryResultRecords.First();   // avoids CopyRec, does not work 

      Ok = true; 
     } 
     return Ok; 
    } 

    private static void CopyRec(MyLab_ClientRef CR_From, MyLab_ClientRef CR_To) 
    { 
     CR_To.UserId = CR_From.UserId; 
     CR_To.ClientId = CR_From.ClientId; 
    } 
} 

我想保持接近得到記錄查詢記錄定義,但不喜歡以這種方式爲每個表類實現CopyRec方法。

有沒有更好的方法來實現呢?我試圖寫this = ...但這是不可能的。

如何編寫比方法A更好的方法B?

回答

0

以下是行不通的:

Why can't I set "this" to a value in C#?

MSDN

如上第一個鏈接顯示,您的最佳選擇仍然是你:爲什麼

this = QueryResultRecords.First(); 

檢查以下鏈接從給定的方法返回MyLab_ClientRef,可以使其靜態和使用,如果爲value or reference分配,在這種情況下,無論是應產生相同的結果

檢查以下,如果這可以在你看來更清潔的實現:

public class MyLab_ClientRef 
{ 
    public int UserId { get; set; } 
    public string ClientId { get; set; } 
    // ... more fields ... 

    public static MyLab_ClientRef GetUser(OracleConnection conn, int UserId, string ClientId) 
    { 
     bool Ok = false; 

     var QueryResultRecords = 
      conn.Query<MyLab_ClientRef>(@"SELECT * FROM MyLab_ClientRef WHERE UserId = :UserId AND ClientId = :ClientId",new { UserId = UserId, ClientId = ClientId }); 

      if(QueryResultRecords.Any()) 
       return QueryResultRecords.First(); 
      else 
       return null;   

    } 
} 

它可以被稱爲:

var newClient = MyLab_ClientRef.GetUser(conn, UserId,ClientId); 

它雖然connection對象是本地的方法,並在using時鐘使用

+0

您的第一個鏈接是非常相關的我的問題。結合您的解決方案和我的類似/簡化問題的評論http://stackoverflow.com/q/33392575/1845672我現在確信C#不能分配給'this',並且單獨的Service類可能會有用。 – Roland