2013-08-17 77 views
0

我正在使用Dapper.net擴展,我希望能夠檢索一個照片對象,並設置'this'而不必單獨設置每個屬性。什麼是實現這一目標的最佳方式?在下面的代碼中,它說我不能分配給'this',因爲它是隻讀的。爲什麼我不能將「this」設置爲C#中的值?

public class Photo 
{ 
    public Int32 PhotoId { get; set; } 
    public Guid ObjectKey { get; set; } 
    public Int16 Width { get; set; } 
    public Int16 Height { get; set; } 
    public EntityObjectStatus ObjectStatus { get; set; } 
    public PhotoObjectType PhotoType { get; set; } 
    public PhotoFormat2 ImageFormat { get; set; } 
    public Int32 CategoryId { get; set; } 

    public Photo(int pPhotoId) 
    { 
     Load(pPhotoId); 
    } 

    public void Load(int pPhotoId) 
    { 
     using (SqlConnection conn = new SqlConnection(Settings.Conn)) 
     { 
      conn.Open(); 
      this = conn.Get<Photo>(pPhotoId); 
     } 
    } 
} 

回答

3

不幸的是,沒有設置屬性就無法做到這一點。一個優雅的方法是使用靜態方法來加載照片。我沒有你使用的擴展名,所以下面的代碼示例有點不同,但它應該作爲一個例子。

using System; 
using System.Collections.Generic; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    public class Photo 
    { 
     public Int32 PhotoId { get; set; } 
     public Guid ObjectKey { get; set; } 
     public Int16 Width { get; set; } 
     public Int16 Height { get; set; } 
     public Int32 CategoryId { get; set; } 

     public static Photo Load(int id) 
     { 
      using (SqlConnection conn = new SqlConnection("ABC")) 
      { 
       return conn.Get<Photo>(id); 
      } 
     } 
    } 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Photo photo = Photo.Load(1); 
     } 
    } 
} 

從這裏喬恩斯基特的話題更多的一些討論:http://bytes.com/topic/c-sharp/answers/513887-cannot-assign-because-read-only

2

this只讀 ...所以不,你不能這樣做。

有框架如AutoMapper用於映射對象。也許你應該研究一下。

這就是說..我認爲你的設計可以使用重新思考。你已經達到了你的域對象自己加載數據的地步,並且你意識到你將會寫出重複的映射代碼。我認爲現在是時候將它提取到一個「服務」類中,並完全從您的域對象中刪除邏輯(因此,使您的問題無效,因爲您無論如何都不會遇到這種情況)。

+0

服務類來處理CRUD操作是我已經實現了一個很好的建議和一個。我探索了一種有效的方法來刪除多餘的代碼,並幫助您的建議! –

2

不能,您必須單獨複製方法,但是您可以使用像反射或AutoMapper之類的方法使其更易於執行。

話雖這麼說,我認爲更好的辦法是讓Load靜態的,有它返回一個新Photo實例,這是你在.NETframeworkitself最常看到的格局。

public static Photo Load(int pPhotoId) 
{ 
    using (SqlConnection conn = new SqlConnection(Settings.Conn)) 
    { 
     conn.Open(); 
     return conn.Get<Photo>(pPhotoId); 
    } 
} 
相關問題