0

I've been trying to persist a concrete class called User which inherits Entity. I can't understand why the Id's are different from the database and debugging the code. I'm using C# with MongoDb.Driver.

public abstract class Entity : IEntity
{
    public Guid Id { get; protected set; }
    public string Description { get; protected set; }
}

public class User : Entity
{
    public string Issuer { get; protected set; }
    public string Subject { get; protected set; }
    public IEnumerable<string> Roles { get; protected set; }

    public User(string issuer, string subject, IEnumerable<string> roles = null)
    {
        Issuer = issuer;
        Subject = subject;
        Roles = roles;
    }
}

For reference, this is my Repository with its Save method.

public class UserRepository
{
    private readonly string _connectionString;
    private readonly string _databaseName;

    protected string CollectionName => "user";

    protected RepositoryAbstract(IMongoStorageConnection mongoStorageConnection)
    {
        _connectionString = mongoStorageConnection.ConnectionString;
        _databaseName = mongoStorageConnection.DatabaseName;
    }

    protected IMongoQueryable<User> MongoCollectionQuery => MongoCollection.AsQueryable();

    protected IMongoCollection<User> MongoCollection => MongoDatabase.GetCollection<User>(CollectionName);

    private IMongoDatabase MongoDatabase => MongoClient.GetDatabase(_databaseName);

    private MongoClient MongoClient
    {
        get
        {
            MongoUrl mongoUrl = new MongoUrl(_connectionString);

            MongoClientSettings settings = MongoClientSettings.FromUrl(mongoUrl);
            settings.SslSettings = new SslSettings
            {
                EnabledSslProtocols = SslProtocols.Tls12
            };

            MongoClient mongoClient = new MongoClient(settings);
            return mongoClient;
        }
    }

    public async Task SaveAsync(User entity) => await MongoCollection.InsertOneAsync(entity);
}

When I try to save a User to the database, the _id field stored in the database is different to the ID that is being shown in my code.

View from Database

View from Code

Can anyone explain why?

chris31389
  • 8,414
  • 7
  • 55
  • 66
  • This thread may help: https://stackoverflow.com/questions/9694460/difference-between-id-and-id-fields-in-mongodb – Roger Roger Sep 19 '17 at 21:17
  • I tried using Mongo labs and azure CosmoDb and it was only on the CosmoDb that the _id field was showing as a LUUID, in Mongo labs db it was something different – chris31389 Sep 20 '17 at 08:13

0 Answers0