Archive

Posts Tagged ‘Linq’

Linq to SQL generic insert, update, delete, GetQueryableList, GetList, GetListAsCsv

July 1st, 2010 No comments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.ComponentModel;

namespace LinqBase
{
public class LinqBase
{
public static MyDataDataContext GetNewDataContext()
{
return new MyDataDataContext();
}

public static IQueryable<T> GetQueryableList<T>() where T : class
{
var store = GetNewDataContext();
return from table in store.GetTable<T>() select table;
}

public static List<T> GetList<T>() where T : class
{
return GetQueryableList<T>().ToList<T>();
}

public static string GetListAsCsv<T>() where T : class
{
return GetCSV<T>(GetQueryableList<T>().ToList<T>());
}

public static void UpdateDatabaseWithItem<T>(T item) where T : class
{
var store = GetNewDataContext();
var table = store.GetTable<T>();
table.Attach(item);
store.Refresh(RefreshMode.KeepCurrentValues, item); //This is a hack but it works
store.SubmitChanges();
}

public static void InsertItemIntoDatabase<T>(T item) where T : class
{
var store = GetNewDataContext();
var table = store.GetTable<T>();
table.InsertOnSubmit(item);
store.SubmitChanges();
}

public static void DeleteItemFromDatabase<T>(T item) where T : class
{
var store = GetNewDataContext();
var table = store.GetTable<T>();
table.Attach(item);
table.DeleteOnSubmit(item);
store.SubmitChanges();
}

public static void EmptyOrTruncateTable(string tableName, bool truncate)
{
var store = GetNewDataContext();

if (truncate)
{
store.ExecuteCommand("TRUNCATE TABLE " + tableName);
}
else
{
GetNewDataContext().ExecuteCommand("DELETE FROM " + tableName);
}

store.SubmitChanges();
}

private static string GetCSV<T>(IList<T> list)
{
StringBuilder sb = new StringBuilder();

//Get the properties for type T for the headers
PropertyInfo[] propInfos = typeof(T).GetProperties();
for (int i = 0; i <= propInfos.Length - 1; i++)
{
sb.Append(propInfos[i].Name);

if (i < propInfos.Length - 1)
{
sb.Append(";");
}
}

sb.AppendLine();

//Loop through the collection, then the properties and add the values
for (int i = 0; i <= list.Count - 1; i++)
{
T item = list[i];
for (int j = 0; j <= propInfos.Length - 1; j++)
{
object o = item.GetType().GetProperty(propInfos[j].Name).GetValue(item, null);
if (o != null)
{
string value = o.ToString();

//Check if the value contans a comma and place it in quotes if so
if (value.Contains(","))
{
value = string.Concat("\"", value, "\"");
}

//Replace any \r or \n special characters from a new line with a space
if (value.Contains("\r"))
{
value = value.Replace("\r", " ");
}
if (value.Contains("\n"))
{
value = value.Replace("\n", " ");
}

sb.Append(value);
}

if (j < propInfos.Length - 1)
{
sb.Append(";");
}
}

sb.AppendLine();
}

return sb.ToString();
}
}
}

Thanks to MattManela

http://blogs.msdn.com/b/matt/archive/2008/08/12/generic-insert-and-update-for-linq-to-sql.aspx