How to convert a T object to an Amazon DynamoDB document dynamically

I am trying to use DynamoDB in Amazon AWS in my MVC.net project. And I'm also trying to execute a multi-level Business-DataAccess-Model project.

I have a GenericDataRepository class that implements the Add () function.

I am sending a T object for Add (), and I would like to convert it to an Amazon Document object, dynamically. How can I do this and what is the best?

public void Add(T entity)
{
    if (entity == null)
        return;

    var doc = new Document();

    // Convert entity to Document automatically
    doc["Title"] = entity.Title;
    doc["Body"] = entity.Body;
    doc["Author"] = entity.Author;
    // Convert entity to Document automatically


    .....
    .....       
    .....
}
+4
source share
3 answers

You can use reflection to dynamically populate a document:

public void Add(T entity)
{
  if (entity == null) 
    return;

  var doc = new Document();
  entity.GetType().GetProperties().ToList().ForEach(x => doc[x.Name] = x.GetValue(entity));
  ...
}
+3
source

, Json.net json, dynamoDb :

var jsonText = JsonConvert.SerializeObject(entity, Formatting.Indented);
var item = Document.FromJson(jsonText);
+2

Remember to add the [Serializable] attribute to your T.

+1
source

Source: https://habr.com/ru/post/1669928/


All Articles