简体   繁体   English

使用 MongoDB 将查询检索为 IQueryable

[英]Retrieve query as IQueryable using MongoDB

I'm updating an old project that implemented the database layer as interfaces so it's easier to add a new database option.我正在更新一个将数据库层实现为接口的旧项目,以便更容易添加新的数据库选项。 I'm currently trying to add MongoDB implementation to it and I've ran into some trouble.我目前正在尝试向其中添加 MongoDB 实现,但遇到了一些麻烦。

The project has an interface called IDataQuery which derives from the the LINQ.IQueryable interface:该项目有一个名为IDataQuery的接口,它派生自LINQ.IQueryable接口:

public interface IDataQuery<out T> : IQueryable<T>
{
}

It also has an interfac called IDataSession which has a Query method that returns this type of IDataQuery :它还有一个名为IDataSession的接口,它有一个Query方法可以返回这种类型的IDataQuery

public interface IDataSession : IDisposable
{
    IDataQuery<T> Query<T>() where T : class, IDataEntity;
}

I've created a class called MongoDataSession which derives from this interface and implements the Query method like so:我创建了一个名为MongoDataSession的类,它派生自这个接口并实现了Query方法,如下所示:

public class MongoDataSession : IDataSession
{
    private IMongoDatabase m_database;

    public MongoDataSession(IMongoDatabase database)
    {
        m_database = database;
    }

    public IDataQuery<T> Query<T>() where T : class, IDataEntity
    {
        var collection = m_database.GetCollection<T>("test");

        return collection.AsQueryable<T>();
    }

    public void Dispose()
    {
        // TODO.
    }
}

However, the MongoDB AsQueryable method returns the result as IMongoQueryable .但是,MongoDB AsQueryable方法将结果返回为IMongoQueryable I tried to cast it to IDataQuery<T> but that didn't work.我试图将它转换为IDataQuery<T>但这没有用。

Solved.解决了。 I created a wrapper around IDataQuery and casted to that.我在IDataQuery周围创建了一个包装器并转换为它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM