使用Find的MongoDB C#GetById

问题描述 投票:2回答:1
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;
    }
}

我正在尝试为MongoDb编写一个通用的抽象存储库类。由于我在基类中使用Generic类型,因此当我使用Find方法查找文档时,“Id”不可见。不确定如何解决问题。

任何帮助,将不胜感激。

c# .net mongodb-.net-driver
1个回答
3
投票

您可以使用Find而不使用带有Builders的类型化lambda表达式:

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

但是,更强大的解决方案是使用一些界面来提供您所需的内容(即ID),并确保GenericRepository仅适用于以下类型:

interface IIdentifiable
{
    string Id { get; }
}

class GenericRepository <T> : ... where T : IIdentifiable
{
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.