Tuesday, February 5, 2013

Copy data from one db to another in linqpad

I wanted to pull a single row of data from one db on one server to another db on another server. using C# and LinqPad. This looks like it would have worked, if I had the matching db on localhost.
void Main()
{
  this.DeferredLoadingEnabled=false; //critical to ignore navigation properties
  var oldcon= this.Connection;
  var user =Users.First (u => u.User_Name=="dummyuser").Dump();
  
  var settings=new Newtonsoft.Json.JsonSerializerSettings(){ NullValueHandling= NullValueHandling.Ignore, ReferenceLoopHandling= ReferenceLoopHandling.Ignore, MaxDepth=1  };
  var serUser= JsonConvert.SerializeObject(user, 
  settings).Dump();
  var myConString=oldcon.ConnectionString.Replace("devdb\\be","localhost").Dump();
  var otherCon= new System.Data.SqlClient.SqlConnection(myConString);
  var otherContext=new TypedDataContext(otherCon); 
  otherContext. Users.Attach((User)JsonConvert.DeserializeObject<User>(serUser.ToString()));
  otherContext.SubmitChanges();
}

2 comments:

  1. This does not work and I do have a matching DB on localhost. I modified the code to match my system and everything looks good. But, the record is not saved to my local.

    My work-around was to execute the 1st part connected to the source DB, then copy/paste the serialized object (single row) to a variable and execute the 2nd part (now very simplified) connected to the destination DB.

    ReplyDelete