Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
    }
}
like image 646
Greg Rogoszewski Avatar asked Aug 17 '13 16:08

Greg Rogoszewski


3 Answers

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"

like image 69
Peter Ritchie Avatar answered Nov 09 '22 11:11

Peter Ritchie


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();
    }
}
like image 41
dRn Avatar answered Nov 09 '22 11:11

dRn


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; }
like image 40
secretwep Avatar answered Nov 09 '22 13:11

secretwep