我正在使用Dapper.net Extensions,我希望能够检索Photo对象并将'this'设置为它,而无需单独设置每个属性。实现这一目标的最佳方法是什么?在下面的代码中,它说我不能分配给'this'因为它只是readonly。
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);
}
}
}
不幸的是,没有设置属性就没有办法做到这一点。一种优雅的方法是使用静态方法加载Photo。我没有你正在使用的扩展,所以下面的代码示例有点不同,但它应该作为一个例子。
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);
}
}
}
Jon Skeet关于这个主题的更多讨论: http : //bytes.com/topic/c-sharp/answers/513887-cannot-assign-because-read-only