Search code examples
c#sqlmongodbwinformsdataadapter

C#-SQL to C#-MongoDB conversion. No DataAdapter for C#-MongoDB?


I have been trying to look for DataAdapter for MongoDB for C# informs application but I can't seem to find it anywhere. Is there even such a thing? I am working on a Login Page where a user enters their username and password and it checks in the database whether such username and password exist or not.

Below is the SQL C# code for creating connection and checking if the username and password exist:

SqlConnection sql_con = new SqlConnection(@"Data Source= xxxxxx");

string query = "SELECT * FROM SignUp WHERE Username = '" + Username_TextBox.Text.Trim() + "' AND Password = '" + Password_TextBox.Text.Trim() + "'";            

SqlDataAdapter sql_da = new SqlDataAdapter(query, sql_con);

DataTable sql_dt = new DataTable();

sql_da.Fill(sql_dt);

if (sql_dt.Rows.Count == 1 && Username_TextBox.Text.Substring(0,4) == "WRDN")
{
    //some code
}

I found this little snippet but it has SQL written in it and the MongoDBConnection and MongoDBDataAdapter do not exist.

string connectionString = "Server=127.0.0.1;Port=27017;";

using (MongoDBConnection connection = new MongoDBConnection(connectionString))
{
    MongoDBDataAdapter dataAdapter = new MongoDBDataAdapter("SELECT City, CompanyName FROM Customers", connection);

    DataTable table = new DataTable();
    dataAdapter.Fill(table);

    Console.WriteLine("Contents of Customers.");

    foreach (DataRow row in table.Rows)
    {
        Console.WriteLine("{0}: {1}", row["City"], row["CompanyName"]);
    }
}

How is this all actually achieved using MongoDB and C#?


Solution

  • Okay, so I found this little package that allows you to use standard drivers to access data from a MongoDB database.

    Step 1: Open Visual Studio > Tools > Manage NuGet Packages and search for CData ADO.NET Provider for MongoDB 2019.

    Step 2: Download and install it.

    Step 3: You'll be prompted to download a key for it. Click OK on the pop-up and your browser will open up and you'll be directed to the download page for it. Click on the Download Trial Key button. Once downloaded, install the key.

    Step 4: Once it's all done, head back to your C# form and insert

    using System.Data.CData.MongoDB;
    

    Now, you can use the MongoDBDataAdapter and MongoDBConnection to access the data from your MongoDB database.