1

I have created an extension method that accepts a JObject and generates an update definition for the C# MongoDB Driver. The idea is that the properties and values in the JObject are used to map to and update properties in the database. However, the update query always throws an exception.

My extension method takes a update definition builder and does the following:

public static UpdateDefinition<T> SetFromPropsInObject<T>(this UpdateDefinitionBuilder<T> builder, object obj) {
  var objType = obj.GetType();
  UpdateDefinition<T> returnBuilder = null;
  var tType = typeof(T);

  if (obj is JObject) {
    var jObj = (JObject)obj;

    foreach (var property in jObj.Properties()) {
      var propFromReflection = TypeDescriptor.GetProperties(tType).Find(property.Name.ToPascalCase(), false);

      if (property.Name.ToLower() != "id" &&
          propFromReflection != null) {
        if (returnBuilder == null) {
          returnBuilder = builder.Set((s) => propFromReflection.GetValue(s), (string)property.Value);
        } else {
          returnBuilder.Set((s) => propFromReflection.GetValue(s), (string)property.Value);
        }
      }
    }
  }

  return returnBuilder;
}

My repository class, that handles interacting with the database, has a method that accepts an object and tries to update the object in the database with the data in the object.

public async Task<UpdateResult> UpdateUser(string id, object updateWith) {
  var filter = Builders<User>.Filter.Eq(s => s.Id, id);
  var update = Builders<User>.Update
                             .SetFromPropsInObject(updateWith);
  return await _dbContext.Users.UpdateOneAsync(filter, update);
}

However, the UpdateOneAsync method call throws the following exception

Unable to determine the serialization information for s =>
value(Namespace.Data.MongoUtilities+<>c__DisplayClass0_0`1[Namespace.Models.User])
.propFromReflection.GetValue(Convert(s)).

I've read about similar issues on Stack Overflow, on how to set properties dynamically using the MongoDB C# Driver, but unfortunately the solution is always simply to just use reflection - which I'm already doing to no avail.

1 Answers1

0

The error says, you can't use propFromReflection.GetValue(s) inside your query. This lambda expression is used to get out the name of the property and it doesn't understand what propFromReflection.GetValue(s) is.

Hasan Emrah Süngü
  • 3,488
  • 1
  • 15
  • 33
  • 1
    That being the case, what is the convention for dynamically getting/setting properties with this driver if I can't use reflection in this way? – John Louderback Mar 22 '17 at 03:38
  • I am not sure I am following your question. It is not for the value, it is for the name of the property. Set operation requires the name of the proeprty – Hasan Emrah Süngü Mar 22 '17 at 03:44