gpt4 book ai didi

c# - MongoDB C# GetById 使用 Find

转载 作者:行者123 更新时间:2023-11-30 21:51:33 25 4
gpt4 key购买 nike

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 编写一个通用的抽象存储库类。由于我在基类中使用通用类型,因此当我使用 Find 方法查找文档时,“Id”不可见。不确定如何解决该问题。

如有任何帮助,我们将不胜感激。

最佳答案

您可以在 Builders 中使用 Find 而无需使用类型化 lambda 表达式:

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

但是,更可靠的解决方案是使用一些接口(interface)来提供您所需的内容(即 ID)并确保 GenericRepository 仅适用于这些类型:

interface IIdentifiable
{
string Id { get; }
}

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

关于c# - MongoDB C# GetById 使用 Find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com