Search code examples
c#.netmongodb-.net-driver

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.


Solution

  • 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
    {
        // ...
    }