How to ignore a class property using Dapper.net Extensions?

9k views Asked by At

I am using Dapper.net Extensions and would like to ignore certain properties without having to write a complete custom mapper. As you can see in the ClassMapper below there is a lot of redundant code when all I really want to do is ignore one property. What would be the best way to accomplish this?

I like the answer provided here https://stackoverflow.com/a/14649356 but I cannot find the namespace where 'Write' is defined.

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

There are 3 answers

1
dRn On

As you can see in Person.cs, just call AutoMap(); in constructor of you ClassMapper. For example:

public class CustomMapper : DapperExtensions.Mapper.ClassMapper<Photo>
{
    public CustomMapper()
    {
        Map(x => x.PhotoId).Key(KeyType.Identity);
        Map(f => f.SomePropertyIDontCareAbout).Ignore();
        AutoMap();
    }
}
2
Peter Ritchie On

The WriteAttribute class is located in the Dapper.Contrib.Extensions namespace--which is part of the Dapper.Contrib project. You can add that via nuget, the package is named "Dapper.Contrib"

1
secretwep On

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