0

我正在使用 Dapper.net Extensions,我希望能够检索一个 Photo 对象并将“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);
        }
    }
}
4

3 回答 3

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);
        }
    }
}

Jon Skeet 在这里就该主题进行了更多讨论:http: //bytes.com/topic/c-sharp/answers/513887-cannot-assign-because-read-only

于 2013-08-17T04:41:33.950 回答
2

this只读的......所以不,你不能那样做。

有像AutoMapper这样的框架用于对象之间的映射。也许你应该调查一下。

话虽这么说..我认为您的设计可以重新考虑。您已经到了域对象自己加载数据的地步,并且您已经意识到您将编写重复的映射代码。我认为是时候将其提取到“服务”类中并从您的域对象中完全删除逻辑(从而使您的问题无效,因为无论如何您都不会遇到这种情况)。

于 2013-08-17T04:37:06.047 回答
2

你不能,你必须单独复制这些方法,但是你可以使用反射之类的方法或 AutoMapper 之类的库来使它更容易做到。

话虽如此,我认为更好的计划是Load静态化并让它返回一个新实例,这是您在.NET框架本身Photo中最常看到的模式。

public static Photo Load(int pPhotoId)
{
    using (SqlConnection conn = new SqlConnection(Settings.Conn))
    {
        conn.Open();
        return conn.Get<Photo>(pPhotoId);
    }
}
于 2013-08-17T04:37:37.350 回答