Joshua
Joshua

Reputation: 2295

MongoDB C# GetById using Find

public abstract class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class
{
    protected SphereTripMongoDbContext SphereTripMongoDbContext;
    public IMongoCollection<T> MongoCollection { get; set; }
    protected GenericRepository(SphereTripMongoDbContext sphereTripMongoDbContext)
    {
        SphereTripMongoDbContext = sphereTripMongoDbContext;
        MongoCollection =
            SphereTripMongoDbContext.MongoDatabase.GetCollection<T>(typeof(T).Name);
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public T GetById(string id)
    {
        var entity = MongoCollection**.Find(t => t.Id == id)**;
        return entity;
    }
}

I am trying write a generic abstract repository class for MongoDb. Since I am using Generic type in the base class, the "Id" is not visible when I am finding the document using Find method. Not sure how to fix the issue.

Any help would be appreciated.

Upvotes: 5

Views: 11240

Answers (2)

crgolden
crgolden

Reputation: 4634

I built a method like this:

public ValueTask<T> GetAsync<T>(IQueryable<T> source, object[] keyValues, CancellationToken cancellationToken = default)
    where T : class
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    if (keyValues == default)
    {
        throw new ArgumentNullException(nameof(keyValues));
    }

    if (keyValues.Length != 1)
    {
        throw new ArgumentException("Key values must contain exactly one key value", nameof(keyValues));
    }

    var type = typeof(T);
    var classMap = BsonClassMap.LookupClassMap(type);
    if (classMap == default)
    {
        throw new InvalidOperationException($"Class map not found for '{type.Name}'");
    }

    var id = classMap.IdMemberMap;
    if (id == default)
    {
        throw new InvalidOperationException($"Id member not found for '{type.Name}'");
    }

    var filter = Builders<T>.Filter.Eq(id.ElementName, keyValues[0]);
    var collection = Database.GetCollection<T>(type.Name);

    async ValueTask<T> GetAsync()
    {
        var cursor = await collection.FindAsync<T>(filter, default, cancellationToken).ConfigureAwait(false);
        return await cursor.SingleOrDefaultAsync(cancellationToken).ConfigureAwait(false);
    }

    return GetAsync();
}

Upvotes: 0

i3arnon
i3arnon

Reputation: 116636

You can use Find without using a typed lambda expression with Builders:

 var item = await collection
    .Find(Builders<ItemClass>.Filter.Eq("_id", id))
    .FirstOrDefaultAsync();

However, a more robust solution would be to use some interface that gives you what you need (i.e. ID) and making sure GenericRepository only works with these types:

interface IIdentifiable
{
    string Id { get; }
}

class GenericRepository <T> : ... where T : IIdentifiable
{
    // ...
}

Upvotes: 13

Related Questions