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类型,因此&#34; Id&#34;我使用Find
方法查找文档时看不到。不确定如何解决问题。
任何帮助都将不胜感激。
答案 0 :(得分: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
{
// ...
}
答案 1 :(得分:0)
我建立了这样的方法:
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();
}