Gre*_*ski 1 c# dapper dapper-extensions
我正在使用 Dapper.net 扩展,我希望能够检索照片对象并将“this”设置为它,而不必单独设置每个属性。实现这一目标的最佳方法是什么?在下面的代码中,它说我无法分配给“this”,因为它是只读的。
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果不设置属性就无法做到这一点。一种优雅的方法是使用静态方法来加载照片。我没有您正在使用的扩展,因此以下代码示例有点不同,但它应该可以作为示例。
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jon Skeet 对此主题进行了更多讨论:http://bytes.com/topic/c-sharp/answers/513887-cannot-assign-because-read-only
| 归档时间: |
|
| 查看次数: |
13206 次 |
| 最近记录: |