I am trying to get into dotnet and Azure and so I build small solution that triggers a azure function by http with a count that then requests the given amount of cat facts from a public api, stores them in a cosmos db and, if the fact is not in my database, dispatches an Event Grid event.
My trouble is about serializing the data for the event and then deserializing it in my event handler.
The data model
public class CatFactDatabaseModel
{
[JsonProperty("id")]
public string? Id;
[JsonProperty("category")]
public string? Category;
[JsonProperty("value")]
public string? Value;
[JsonProperty("valueHash")]
public string? ValueHash;
}
The way I pass data to the event
foreach (var item in dbUpdateItems)
{
var i = JsonConvert.SerializeObject(item);
log.LogInformation($"SERIALIZED ITEM: {i}");
var e = new EventGridEvent("add-catFact", "add-catFact", "1.0", i);
await collector.AddAsync(e);
}
where dbUpdateItems is a list of CatFactDatabaseModel.
The code to deserialize the Event
public static void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
{
var any = JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
var data = JsonConvert.DeserializeObject<CatFactDatabaseModel>(any.ToString());
log.LogInformation($"Added message was {data.Value}");
}
The Question is:
Why do I need to deserialize the EventGridEvent twice?
I tried to skip the serializing in the event creating, but then I just get empty data in the event. If I deserialize only once into CatFactDatabaseModel, I get errors. If I deserialize without a type, it becomes an escaped string.
I tried to read the data as JObject instead of EventGridEvent, but that turns out the be the same with extra steps.
I tried to deserialize with
var data = eventGridEvent.Data.ToObjectFromJson<CatFactDatabaseModel>();
but it's not working either This is the only way it turned out as an actual, non empty object of type CatFactDatabaseModel, but I don't think this is how it is supposed to be.
I think the actual error is on the event creation part, but I could not find a solution with the documentation or googling stuff.
What am I doing wrong?