Instead of creating a ForEach statement to do a MongoDB insert statement for each record I would like to select all the records using Linq from SQL Server and insert all of them as one insert statement. I have the following code below and there are no errors, but it only inserts the first record.
DataSet myDataSet1 = new DataSet();
string connectionString = ConfigurationManager.ConnectionStrings["SQLServerConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ClassTest", connection);
cmd.CommandType = CommandType.StoredProcedure;
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable classy = new DataTable();
da.Fill(classy);
//INSERT WEBSITE ACTIVITY
string connectionStringMongo = System.Configuration.ConfigurationManager.ConnectionStrings["MongoDBConnectionString"].ConnectionString;
MongoServer server = MongoServer.Create(connectionStringMongo);
MongoDatabase patheerdb = server.GetDatabase("ClassTest");
MongoCollection<BsonDocument> usershistory =
patheerdb.GetCollection<BsonDocument>("userhistory");
List<string> userallrecords = new List<string>();
var query = classy.AsEnumerable().Select(newclass => new
{
KEY = newclass.Field<int?>("KEY"),
EVENT_TYPE = newclass.Field<string>("EVENT_TYPE"),
USER_IDENTIFIER = newclass.Field<string>("USER_IDENTIFIER"),
COURSE_IDENTIFIER = newclass.Field<int?>("COURSE_IDENTIFIER"),
GROUP_ID = newclass.Field<string>("GROUP_ID"),
FORUM_ID = newclass.Field<string>("FORUM_ID"),
INTERNAL_HANDLE = newclass.Field<string>("INTERNAL_HANDLE"),
CONTENT_ID = newclass.Field<int?>("CONTENT_ID"),
DATA = newclass.Field<string>("DATA"),
TIMESTAMP = newclass.Field<DateTime>("TIMESTAMP"),
SESSION_ID = newclass.Field<int?>("SESSION_ID")
});
string rawJson = JsonConvert.SerializeObject(query);
rawJson = rawJson.Remove(rawJson.Length - 1);
rawJson = rawJson.Remove(0, 1);
usershistory.InsertBatch(query.Select(x => BsonDocument.Parse(x.ToString())));
Label1.Text = rawJson;
}