4 ms·
I agree with the article and try to use write my queries with Linq instead of SQL almost always. The article says to avoid using Linq for bulk inserts, but for
by yellowstuff 10y ago
I agree with the article and try to use write my queries with Linq instead of SQL almost always.
The article says to avoid using Linq for bulk inserts, but for years I've been using an extension method to translate Linq to a bulk insert and it works fine. I forget where I found it.
public static class DataContextExtension
{
public static void BulkInsertAll<T>(this DataContext dc, IEnumerable<T> entities)
{
using (var conn = new SqlConnection(dc.Connection.ConnectionString))
{
conn.Open();
Type t = typeof(T);
var tableAttribute = (TableAttribute)t.GetCustomAttributes(
typeof(TableAttribute), false).Single();
var bulkCopy = new SqlBulkCopy(conn)
{
BulkCopyTimeout = 1200,
DestinationTableName = tableAttribute.Name
};
var properties = t.GetProperties().Where(EventTypeFilter).ToArray();
var table = new DataTable();
foreach (var property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
table.Columns.Add(new DataColumn(property.Name, propertyType));
}
foreach (var entity in entities)
{
table.Rows.Add(
properties.Select(
property => property.GetValue(entity, null) ?? DBNull.Value
).ToArray());
}
bulkCopy.WriteToServer(table);
}
}
private static bool EventTypeFilter(System.Reflection.PropertyInfo p)
{
var attribute = Attribute.GetCustomAttribute(p,
typeof(AssociationAttribute)) as AssociationAttribute;
if (attribute == null) return true;
if (attribute.IsForeignKey == false) return true;
return false;
}
}
- NicoJuicy 10y agoI'm actually doing something else when updating a webshop from a remote source.. I convert all objects that i import to a big SQL Query. Something like First query: UPDATE table SET active=0; Second ( big ) query: UPDATE table SET properties=values IF ROWCOUNT =0 INSER INTO table(properties)VALUES(values)