1

I have an SQLite database with an event table consisting of four columns: id (INT), timestamp (TEXT), level (TEXT) and message (TEXT). When I read back events, I want to convert the level values to corresponding LogLevel enum values. The text values are the same as the enum member names. How can I do this? I see that if I use Query<object> I get a list where I can enumerate through all rows and cast them before adding them to new Event struct values. But is this the best/easiest way to do this?

public struct Event
{
    public Event(DateTime timestamp, LogLevel level, string message)
    {
        Timestamp = timestamp;
        Level = level;
        Message = message;
    }
    public DateTime Timestamp { get; }
    public LogLevel Level { get; }
    public string Message { get; }
}

public enum LogLevel
{
    FATAL,
    ERROR,
    WARN,
    INFO
}

public List<Event> GetNewEvents(uint rowId)
{
    var events = _dbConnection.Query<Event>("SELECT * FROM events WHERE id >= @RowId;", new { RowId = rowId });
    return events.ToList();
}

1 Answer 1

2

Dapper will automatically map enum values if your 'level' column values matches with enum values. However you might have problem with that constructor. Also not sure why you have used struct. Just change your event to struct to class below.

public class Event
{           
    public DateTime Timestamp { get; set; }
    public LogLevel Level { get; set; }
    public string Message { get; set; }
}

Rest is the same.

Sign up to request clarification or add additional context in comments.

4 Comments

I used a struct since I figured it was just a placeholder for values, which would never change when created. Actually, it doesn't seem to matter if I use a struct or a class. The problem was the constructor, as you pointed out.
But that said, why should I use a class and not a struct in this case? Both works just the same, from what I see.
In your case there is no difference. Both will work fine. It's just rule of thumb.
What is the rule of thumb? You're just telling me to change from struct to class, but not why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.