简体   繁体   中英

Clearing MongoDb keys on IIS website

New to IIS and Mongo, and I'm trying to find a way to clear the keys from my server to avoid an "item with the same key has already been added" exception.

IMongoDatabase _db;
IMongoCollection<BoardStorageItem> _boardsCollection;
public MongoDb()
    {
        var client = new MongoClient("mongodb://localhost");
        _db = client.GetDatabase("KanbanDemonstration");

        BsonClassMap.RegisterClassMap<CardStorageItem>();
        BsonClassMap.RegisterClassMap<ColumnStorageItem>();
        BsonClassMap.RegisterClassMap<BoardStorageItem>();
        BsonClassMap.RegisterClassMap<EmployeeStorageItem>();


        _boardsCollection = _db.GetCollection<BoardStorageItem>("Board");
    }

    public BoardStorageItem GetBoardByName(string name)
    {
        var board = _boardsCollection.AsQueryable().FirstOrDefault(b => b.Name == name);
        return board;
    }

public class MongoConverter
{
    MongoDb _mongoDb;

    public MongoConverter()
    {
        _mongoDb = new MongoDb();
    }

    public BoardStorageItem GetBoardByName(string name)
    {
        return _mongoDb.GetBoardByName(name);
    }
}

and then for the code on the web page itself

protected void Button1_Click(object sender, EventArgs e)
{
    _mongoConverter = new MongoConverter();
    var board = _mongoConverter.GetBoardByName(TextBox1.Text);

    BoardName = board.Name;
    BoardId = board.Id;

    Label3.Text = BoardName;
    Label4.Text = BoardId;

    Session.Clear();
}

This works perfectly this first time I use the button to get a board, but if I try a second time, I get an exception "item with the same key has already been added" when attempting to new up MongoConverter. I had thought that clearing the session after would clear out the keys as well, but the only thing that seems to work is resetting the server itself.

Calling BsonClassMap.RegisterClassMap<T>() should only be done once per type. And it should be done at application startup, before opening any database connections according to the documentation .

Since you're in ASP.NET, put this in your Application_Start event in your global application class (global.asax)

void Application_Start(object sender, EventArgs e)
{
    BsonClassMap.RegisterClassMap<CardStorageItem>();
    BsonClassMap.RegisterClassMap<ColumnStorageItem>();
    BsonClassMap.RegisterClassMap<BoardStorageItem>();
    BsonClassMap.RegisterClassMap<EmployeeStorageItem>();
}

You can make another method that calls it so you don't pollute your global application class if you want. And of course, remove the registrations from your constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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