Reputation: 1322
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();
}
Upvotes: 1
Views: 784
Reputation: 1123
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.
Upvotes: 2