Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;

    }
share|improve this question
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.