Skip to content

Instantly share code, notes, and snippets.

@Jtorrecilla
Created February 14, 2016 19:55
Show Gist options
  • Select an option

  • Save Jtorrecilla/0906a7ffa3cf0904a360 to your computer and use it in GitHub Desktop.

Select an option

Save Jtorrecilla/0906a7ffa3cf0904a360 to your computer and use it in GitHub Desktop.
public class SqlCopy : IDisposable
{
private DbConnection originConnection;
private DbConnection destinationConnection;
private ISqlQueryGeneration queryGenerator;
private List<ReferentialConstraintAssociation> constraintAssociation;
public SqlCopy(ISqlQueryGeneration generator, DbConnection origin, DbConnection destination)
{
if (origin == null)
{
throw new ArgumentNullException("Origin connection should not be null.");
}
if (destination == null)
{
throw new ArgumentNullException("Destination connection should not be null.");
}
constraintAssociation = new List<ReferentialConstraintAssociation>();
queryGenerator = generator;
originConnection = origin;
destinationConnection = destination;
}
public void CopyData<T>()
{
var columns= ColumnsGetter.GetColumns(typeof(T));
var tableName = typeof(T).Name;
var selectQuery = queryGenerator.GetSelectQuery(columns,tableName);
var insertQuery = queryGenerator.GetInsertQuery(ColumnsGetter.ExcludeId(columns), tableName, true);
var selectResult = originConnection.Query<T>(selectQuery);
var constraint = new ReferentialConstraintAssociation();
constraint.ForeignKeyNames.Add(string.Format("{0}Id", tableName));
foreach (var item in selectResult)
{
var itemForInsert = ReplaceConstraints(item);
var newId = destinationConnection.ExecuteScalar<int>(insertQuery, itemForInsert);
constraint.MatchingReferenceDictionary.Add(GetIdValue(item), newId);
}
constraintAssociation.Add(constraint);
}
public void Dispose()
{
originConnection.Dispose();
destinationConnection.Dispose();
}
private int GetIdValue<T>(T item)
{
var property = item.GetType().GetProperty("Id");
if (property!=null)
{
return Convert.ToInt32(property.GetValue(item, null));
}
return -1;
}
private T ReplaceConstraints<T>(T item) {
var properties = item.GetType().GetProperties();
foreach (var constraint in constraintAssociation)
{
foreach (var constraintName in constraint.ForeignKeyNames)
{
var property = properties.FirstOrDefault(prop => prop.Name.Equals(constraintName, StringComparison.InvariantCultureIgnoreCase));
if (property!=null){
var newValue = constraint.MatchingReferenceDictionary.FirstOrDefault(key=>key.Key.Equals(property.GetValue(item,null)));
property.SetValue(item,newValue.Value,null);
}
}
}
return item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment