c# - MongoDb 使用新的异步方法创建存储库模式

标签 c# mongodb mongodb-.net-driver mongodb-csharp-2.0

public class MongoDbRepository<T> : IRepository<T> where T : IEntityBase
{
    private IMongoDatabase database;
    private IMongoCollection<T> collection;

    public MongoDbRepository()
    {
        GetDatabase();
        GetCollection();
    }

    private void GetDatabase()
    {
        var client = new MongoClient(GetConnectionString());
        database = client.GetDatabase(GetDatabaseName());
    }

    private void GetCollection()
    {
        collection = database.GetCollection<T>(typeof(T).Name);
    }

    private string GetDatabaseName()
    {
        return ConfigurationManager.AppSettings.Get("MongoDbDatabaseName");
    }

    private string GetConnectionString()
    {
        return ConfigurationManager.AppSettings.Get("MongoDbConnectionString").Replace("{DB_NAME}", GetDatabaseName());
    }


    public async Task<IList<T>> SelectAllSync() 
    {
     //Add _id that is unique for each document
     var filter = new BsonDocument("_id", new BsonDocument("$exists", true));
     var people = await collection.Find<T>(filter).ToListAsync<T>();

        //Search methods
        var result1 = await database.GetCollection<T>(typeof(T).Name)
                                .Aggregate()
                                .Match(x => x.last_name.Equals("Hall")).ToListAsync();


        var result2 = collection.FindAsync<T>(Builders<T>
                            .Filter.Eq(x => x.last_name, "Grammer")
                            , new FindOptions<T> { Comment = "TEST" }
                            , CancellationToken.None);

        var result3 = await collection.FindAsync<T>(
                           Builders<T>.Filter.Eq("dealership_name", "D-PATRICK NISSAN"),
                           new FindOptions<T> { Comment = "TEST" },
                           CancellationToken.None);



        return (IList<T>)people;
    }

    public Task Insert(T entity)
    {
        var result = collection.InsertOneAsync(entity);
        return  result;
    }

    public async Task<DeleteResult> Delete(T entity)
    {
        var deleteResult = await collection.DeleteOneAsync(Builders<T>.Filter.Eq(s => s._id, entity._id));
        return deleteResult;
    }

    public async Task<IList<T>> SearchFor(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        var result = await database.GetCollection<T>(typeof(T).Name)
                                .Aggregate()
                                .Match(predicate).ToListAsync();
        return result;
    }

    public async Task<IList<T>> GetById(ObjectId id)
    {
        var result = await database.GetCollection<T>(typeof(T).Name)
                                .Aggregate()
                                .Match(x => x._id.Equals(id)).ToListAsync();
        return result;
    }

    public async Task<UpdateResult> Update(T entity)
    {
        if (entity._id == null)
            await Insert(entity);

// Added list of string values for dealer_code

        var list = new List<string>();
        list.Add("dealer_code");
        var result = await collection.UpdateOneAsync(
             Builders<T>.Filter.Eq(s => s.dealer_code, entity.dealer_code),
             Builders<T>.Update.AddToSet(list[0], entity.dealer_code)
                                      );

        return result;
    }
}

我的更新方法有问题。它给了我:

"The serializer for field 'dealer_code' must implement IBsonArraySerializer and provide item serialization info."

这是什么意思?我该如何解决这个问题?

最佳答案

 public class MongoDbRepository<T> : IRepository<T> where T : IEntityBase
{
    private IMongoDatabase database;
    private IMongoCollection<T> collection;

    public MongoDbRepository()
    {
        GetDatabase();
        GetCollection();
    }

    private void GetDatabase()
    {
        var client = new MongoClient(GetConnectionString());
        database = client.GetDatabase(GetDatabaseName());
    }

    private void GetCollection()
    {
        collection = database.GetCollection<T>(typeof(T).Name);
    }

    private string GetDatabaseName()
    {
        return ConfigurationManager.AppSettings.Get("MongoDbDatabaseName");
    }

    private string GetConnectionString()
    {
        return ConfigurationManager.AppSettings.Get("MongoDbConnectionString").Replace("{DB_NAME}", GetDatabaseName());
    }


    public async Task<IList<T>> SelectAllSync() 
    {

        //var filter = new BsonDocument("dealer_code", new BsonDocument("$exists", true));
        //var people = await collection.Find<T>(filter).ToListAsync<T>();

        //Search methods
        var result1 = await database.GetCollection<T>(typeof(T).Name)
                                .Aggregate()
                                .Match(x => x.last_name.Equals("Hall")).ToListAsync();


        var result2 = collection.FindAsync<T>(Builders<T>
                            .Filter.Eq(x => x.last_name, "Grammer")
                            , new FindOptions<T> { Comment = "TEST" }
                            , CancellationToken.None);





        return (IList<T>)result1;
    }

    public Task Insert(T entity)
    {
        var result = collection.InsertOneAsync(entity);
        return  result;
    }

    public async Task<DeleteResult> Delete(T entity)
    {
        var deleteResult = await collection.DeleteOneAsync(Builders<T>.Filter.Eq(s => s._id, entity._id));
        return deleteResult;
    }

    public async Task<IList<T>> SearchFor(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        var result = await database.GetCollection<T>(typeof(T).Name)
                                .Aggregate()
                                .Match(predicate).ToListAsync();
        return result;
    }

    public async Task<IList<T>> GetById(ObjectId id)
    {
        var result = await database.GetCollection<T>(typeof(T).Name)
                                .Aggregate()
                                .Match(x => x._id.Equals(id)).ToListAsync();
        return result;
    }

    public async Task<UpdateResult> Update(Expression<Func<T, bool>> filter,T entity) 
    {
        if (entity._id == null)
            await Insert(entity);

        var list = new List<string>();
        list.Add("dealer_code");

        var result = await collection.UpdateOneAsync(
                                Builders<T>.Filter.Where(filter),
                                Builders<T>.Update.Set(x=>x.dealer_code, entity.dealer_code));

        if (result.IsAcknowledged)
        {
            Console.WriteLine("Success");
        }
        return result;
    }
}

当我更改 Update.Set() 而不是 Update.AddToSet() 时,它终于开始工作

关于c# - MongoDb 使用新的异步方法创建存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30190669/

相关文章:

MongoDB C# 驱动程序不自动映射 pascal 大小写的属性

c# - MongoDB C# 驱动程序 : How do I ensure an index using LINQ expressions on the contents of an array?

c# - 如何以特定间隔更新动态 DOM 值?

C# 类库异常处理

c# - 如何在 Visual Studio 2013 中安装 MongoDB.Driver

mongodb - 如何在 MongoDB 中使用深度查询获取 `find()` 数据?

python - 在 Mongodb 中存储 Numpy 或 Pandas 数据

c# - c#中的引用类型和值类型有什么区别?

c# - EntityFramework Core 2.2 到 3.1.1 出现错误

ruby - 列出 Mongoid 模型中的动态属性