spruce-net/spruce

Enum field value as string

jwynveen opened this issue · 2 comments

When marking an enum field with [StringLength(50)] to make it a string field, I would expect the value of the field to be the string representation of the enum value, not the integer value of the enum. See the below failing test. I'm not sure if this is intended behavior or not, so I didn't make a pull request for this. I could see the other side of the behavior where someone has defined specific integers to each enum value and you'd want those to be stored instead, so this might be up for debate.

private enum ClassEnumToMap
{
    Value1
}
private class ClassWithEnumField
{
    [AutoIncrement]
    public int Id { get; set; }
    [StringLength(50)]
    public ClassEnumToMap EnumField { get; set; }
}
[Test]
public void Four_GivenEnumFieldMappedToString_UsesStringValueOfEnum()
{
    var item = new ClassWithEnumField
    {
        EnumField = ClassEnumToMap.Value1
    };
    Db.Save(item);

    var getItems = Db.Query<dynamic>(string.Format("select * from [{0}] where Id=@id", Db.GetTableName<ClassWithEnumField>()),
        new {item.Id});
    getItems.Should().Not.Be.Null();
    getItems.Should().Count.Exactly(1);
    var getItem = getItems.FirstOrDefault();
    Assert.AreEqual("Value1", getItem.EnumField.ToString());   //Fails: Expected: "Value1"  But was:  "0"
}

My take is that if stringlength is specified, then we should store the string representation of the enum, not the integer value as a string.

From what I see, the creation of the query parameters happens inside of Dapper, so I'm not sure how to make this happen. Did some quick searching regarding the mapping of enums with dapper but don't see a simple solution. Hopefully you can think of a way to work around it.