6

我正在使用 Dapper.net Extensions 并且想忽略某些属性而不必编写完整的自定义映射器。正如您在下面的 ClassMapper 中看到的那样,当我真正想做的只是忽略一个属性时,会有很多冗余代码。实现这一目标的最佳方法是什么?

我喜欢这里提供的答案https://stackoverflow.com/a/14649356但我找不到定义“写入”的命名空间。

public class Photo : CRUD, EntityElement
{
    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 int SomePropertyIDontCareAbout { get; set; }
}


public class CustomMapper : DapperExtensions.Mapper.ClassMapper<Photo>
{
    public CustomMapper()
    {
        Map(x => x.PhotoId).Column("PhotoId").Key(KeyType.Identity);
        Map(x => x.ObjectKey).Column("ObjectKey");
        Map(x => x.Width).Column("Width");
        Map(x => x.Height).Column("Height");
        Map(x => x.ObjectStatus).Column("ObjectStatus");
        Map(x => x.PhotoType).Column("PhotoType");
        Map(x => x.ImageFormat).Column("ImageFormat");
        Map(x => x.CategoryId).Column("CategoryId");

        Map(f => f.SomePropertyIDontCareAbout).Ignore();
    }
}
4

3 回答 3

5

该类WriteAttribute位于Dapper.Contrib.Extensions命名空间中——它是 Dapper.Contrib 项目的一部分。您可以通过 nuget 添加它,该包名为“Dapper.Contrib”

于 2013-08-17T22:02:52.523 回答
4

正如您在Person.cs中看到的,只需调用AutoMap();您的构造函数即可ClassMapper。例如:

public class CustomMapper : DapperExtensions.Mapper.ClassMapper<Photo>
{
    public CustomMapper()
    {
        Map(x => x.PhotoId).Key(KeyType.Identity);
        Map(f => f.SomePropertyIDontCareAbout).Ignore();
        AutoMap();
    }
}
于 2013-08-29T17:46:15.133 回答
4

You can decorate the property with [Computed] and the property will be ignored on insert. Semantically it may not be perfect but it seems to do the job:

[Computed]
public int SomePropertyIDontCareAbout { get; set; }

Then again, Peter Ritchie's answer is likely more spot-on with:

[WriteAttribute(false)]
public int SomePropertyIDontCareAbout { get; set; }
于 2016-04-21T17:52:31.080 回答