C#Mongo驱动程序 - FindAsync问题

问题描述 投票:-1回答:1

我一直在构建一个基本的MVC应用程序,并且已经厌倦了几件事。主要是在mongodb中连接并找到一些东西。我一直在努力实现泛型。下面我提供了一些代码来向您展示我想要实现的内容。我认为我的问题是从数据库中获取正确的集合,但是我遇到的下一个问题是从T转换为User。

我一直在尝试不同的方法来解决这个问题,但是我已经被困了很长一段时间了。我实现了一个使用'ConnectToMongo'函数的Create函数,并且该函数可以正常工作,但是当我尝试实现find或findbyexpression并遇到这些错误时。我希望有人能指出我正确的方向,谢谢。

    /// <summary>
    /// Finds the object by expression.
    /// </summary>
    /// <returns>The object by expression.</returns>
    /// <param name="entity">Entity.</param>
    /// <param name="expression">Expression.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    private async Task<T> FindObjectByExpression<T>(T entity, Expression<Func<T, bool>> expression)
    {
        T result;

        try
        {
            var collection = this.ConnectToMongo(entity);
            if (collection == null)
            {
                Console.WriteLine($"Collection: {entity.GetType()} does not exsit.");
                return default(T);
            }

            var filterDefinition = Builders<T>.Filter.Where(expression);
            result = (T)await collection.FindAsync(filterDefinition);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return default(T);
        }

        return result;
    }

    /// <summary>
    /// Connects to mongo.
    /// </summary>
    /// <returns>The to mongo.</returns>
    /// <param name="entity">Entity.</param>
    private IMongoCollection<T> ConnectToMongo<T>(T entity)
    {
        IMongoCollection<T> collection = null;
        try
        {
            MongoClientSettings setting = new MongoClientSettings
            {
                Server = new MongoServerAddress("localhost", 27017)
            };
            MongoClient client = new MongoClient(setting);
            var mongoDbServer = client.GetDatabase(DBName);

            collection = mongoDbServer.GetCollection<T>($"{entity.GetType().Name}");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);

        }
        return collection;
    }

 public abstract class Command
 {
    public Command(Guid? ID)
    {
       if(ID == null)
       {
          ID = Guid.NewGuid();
       }
       else
       {
          this.ID = ID.Value;
       }
     }

    [BsonId]
    public Guid ID { get; set; }

    public string Email { get; set; }
    public string Password { get; set; }
}

public class User : Command
{
    public User(Guid? Id)
        : base(Id)
       {
        this.classDictionary = new Dictionary<string, string>();
    }

    [Required]
    public Entitlement UserEntitlement { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    public string UniID { get; set; }

    // Maps from Course ID to Section ID
    public Dictionary<string, string> classDictionary { get; set; }
}

public enum Entitlement
{
    Student = 10,
    Admin = 20,
    Bot = 30,
    Unknown = 0
}
c# mongodb generics mongodb-.net-driver
1个回答
0
投票

我需要改变这一行

result = (T)await collection.FindAsync(filterDefinition);

到这条线

var results = await collection.Find(filterDefinition).ToListAsync();
result = results.FirstOrDefault();

它试图将IAsyncCursor强制转换为T.

© www.soinside.com 2019 - 2024. All rights reserved.