less than 1 minute read

You can get rid of the dependency from the domain model to MongoDB assemblies, by utilizing Class Map functionality of the Official MongoDB C# Driver.

It is simple to use the property mapping, but you can also use AutoMap combined with one or more overriding mappings. That is often useful when using the MongoDB IdGenerators. However, how do you specify which to use without using attributes?

Below is a simple class with no dependencies – only dependent on the .NET Base Class Library:

public class Person
{
  public string Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Notice that not event an ObjecId is present. To instruct MongoDB to generate a unique identifier for the Id property:

public class Person
{
  [BsonId]
  public string Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

But now there is a dependency on the BSonId attribute. We can remove it via a Class Map:

BsonClassMap.RegisterClassMap(cm =>
            {
                cm.AutoMap();
                cm.SetIdMember(cm.GetMemberMap(x => x.Id)
                  .SetIdGenerator(StringObjectIdGenerator.Instance));
            });

It is possible to use other data types as unique identifiers; just choose the correspond IdGenerator.

Comments