Question about associating enums with a class

This might be a bit lengthy, but I was hoping you guys could give me some insight as to whether or not I'm approaching this correctly.

I've been experimenting with a logging mechanism for my application, and rather than create several different "log" tables (e.g. CustomerLogs, ProductLogs, etc), I am just using one. This has so far proved to be fairly convenient, and I'd like to keep this structure, but I have a question regarding one aspect.

The table contains a special column called "Details", which I am populating with JSON serialized info of whatever a particular log requires. For example, logging that a product's name was changed would insert a new log record that would look something like this:

Category: "Product" Event: "ProductNameChanged" Details: "{ OldName: 'The old product name', NewName: 'The new product name' }" 

The Category and Event columns are just to give an idea of how I am fetching these records, but the Details column is what I'd like to focus on. When fetching these events, I'd like to have some mechanism that auto-deserializes the Details column to a strongly-typed class, mainly so I can render these on a page without littering my views with something along the lines of:

@if(logRecord.Event == Events.ProductNameChanged) { var resolved = JSON.Deserialize<MyProductNameChangedResolver>(logRecord.Details); <p>Name was changed from @resolved.OldName to @resolved.NewName</p> } 

Ideally, I'd like to perform the deserialization immediately upon fetching the logs I desire.

So my problem is figuring out the cleanest way to assign an event with the aforementioned resolver. Right now I'm tinkering with this sort of approach:

public enum LogEvent { ... [TypeConverter(typeof(MyProductNameChangedResolver))] ProductNameChanged = 100, ProductDeleted = 101, ... } 

My thought process is that I could then use this attribute to get the resolver, and execute a deserialize method to actually acquire the object as needed.

Is there a smarter approach to this? I have considered using a Dictionary but doing so would make my ORM (Dapper) work a bit harder to map the object to its respective resolver.

The obvious downside to this is that I'd have to use reflection to get the resolver class, but I'm not entirely sure what the overhead would look like if this were for ~15-50 log records.

Any help/discussion would be much appreciated. And sorry for such a long post… I know asking to help out with this is a lot to ask.

by fbmgriever via /r/csharp

Leave a Reply