Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-2572

Custom Serializer - Querying with LINQ

    XMLWordPrintable

    Details

      Description

      Hi!
      I made a generic custom serializer implementing IBsonDocumentSerializer and IBsonSerializer interfaces. It works very well to insert/update documents on the database, but I'm having some troubles on read operations when using LINQ. Consider the following example classes:

      public class RootClass
      {
          public string Id {get; set; }
          public NewClass NewClass {get; set; }
      }
      

      public class NewClass
      {
          public int NewProperty {get; set; }
      }
      

      And here's my implementation of "TryGetMemberSerializationInfo":

      public class CustomSerializer<T> : IBsonDocumentSerializer, IBsonSerializer<T> where T : class
      {
          public Type ValueType => typeof(T);
       
          public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
          {
              var propTypeName = ValueType.GetProperty(memberName).PropertyType.Name;
              serializationInfo = new BsonSerializationInfo(memberName, GetProperlyBsonSerializer(propTypeName), typeof(string));
              return serializationInfo != null;
          }
       
          private IBsonSerializer GetProperlyBsonSerializer(string propName)
          {
              switch (propName)
              {
                  case "Int32":
                      return new MongoDB.Bson.Serialization.Serializers.Int32Serializer();
                  case "String":
                      return new MongoDB.Bson.Serialization.Serializers.StringSerializer();
                  default:
                      return null;
              }
          }
      }
      

      When I query my DB using LINQ operators and the conditional parameter is a property from another object that is accessed by a navigation property, like this:

      var return = rootClassCollection.AsQueryable().FirstOrDefault(x => x.NewClass.NewProperty == 1);
      

      The memberName parameter receives the value "NewClass", instead of "NewProperty", so I can't classify the type correctly, generating an exception.
      This problem doesn't happens when I use a parameter that isn't a navigation property, like this:

      var return = rootClassCollection.AsQueryable().FirstOrDefault(x => x.Id.Equals("AB123"));
      

      I think that this issue is nearly the same issue described in CSHARP-1755, however, since it was discussed almost 3 years ago, any new recommendations?
      Thanks in advance!

        Attachments

          Activity

            People

            • Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

              • Created:
                Updated: