Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 543
Joshua Avatar asked Mar 13 '23 05:03

Joshua


1 Answers

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
{
    // ...
}
like image 162
i3arnon Avatar answered Apr 19 '23 11:04

i3arnon