Can Odata Metadata be cached in Distributed cache?

Viewed 285

Is there a way to cache the metadata (EdmModel) in distributed cache?

We have a multi-tenant system where metadata can change depending on the client. We are currently building up the metadata for a client, then caching it InMemory. It is expensive building up this metadata so we have to cache it.

It looks like it is not possible to serialize the EdmModel using binary serialization and then cache it using a distributed cache like Redis.

I have the following code to serialize the model, but it does not work.

IEdmModel model = GetEdmModel();
using (MemoryStream memorystream = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(memorystream, model);  // Error is thrown here
    byte[] yourBytesToDb = memorystream.ToArray();
}

I get the following error

Type 'Microsoft.OData.Edm.EdmModel' in Assembly 
'Microsoft.OData.Edm, Version=7.7.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' 
is not marked as serializable.

Is there another way to serialize the Model?

1 Answers

You can try looking at the following.

https://docs.microsoft.com/en-us/odata/odatalib/edm/read-write-model

private byte[] ConvertToBytes(IEdmModel model)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(memoryStream))
        {
            IEnumerable<EdmError> errors;
            CsdlWriter.TryWriteCsdl(model, writer, CsdlTarget.OData, out errors);
        }
        return memoryStream.ToArray();
    }
}

private IEdmModel ConvertFromBytes(byte[] modelBytes)
{
    using (var ms = new MemoryStream(modelBytes))
    {
        using (var reader = XmlReader.Create(ms))
        {
            IEnumerable<EdmError> errors;
            IEdmModel model;
            if (CsdlReader.TryParse(reader, out model, out errors))
            {
                return model;
            }
            throw new InvalidOperationException($"Model Error: {string.Join(",", errors.Select(_ => _.ErrorMessage))}");
        }
    }
}
Related