Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Created November 2, 2012 13:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/4001262 to your computer and use it in GitHub Desktop.
Save bradoyler/4001262 to your computer and use it in GitHub Desktop.
A DataContext wrapper for LINQ to SQL model.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Common;
using System.Data.Linq;
namespace MyApp.Models.DataContextWrapper
{
public interface IDataContextWrapper
{
void DeleteOnSubmit<T>(T entity) where T : class;
void DeleteAllOnSubmit<T>(IEnumerable<T> entities) where T : class;
void InsertOnSubmit<T>(T entity) where T : class;
void InsertAllOnSubmit<T>(IEnumerable<T> entities) where T : class;
void SubmitChanges();
IQueryable<T> Table<T>() where T : class;
IQueryable<T> Query<T>() where T : class;
IEnumerable<TResult> ExecuteQuery<TResult>(string query, params object[] parameters);
DbConnection Connection();
}
public abstract class DataContextWrapper : IDataContextWrapper
{
protected DataContext Db;
public DataContextWrapper(DataContext context)
{
this.Db = context;
}
public DataContextWrapper(DataContext context, DataContextConfig conn)
{
context.Connection.ConnectionString=conn.ConnectionString;
this.Db = context;
}
public IQueryable<T> Table<T>() where T : class
{
return Db.GetTable<T>().AsQueryable();
}
public IQueryable<T> Query<T>() where T : class
{
return Db.GetTable<T>().AsQueryable();
}
public void DeleteOnSubmit<T>(T entity) where T : class
{
Db.GetTable<T>().DeleteOnSubmit(entity);
}
public void DeleteAllOnSubmit<T>(IEnumerable<T> entities) where T : class
{
Db.GetTable<T>().DeleteAllOnSubmit(entities);
}
public void InsertOnSubmit<T>(T entity) where T : class
{
Db.GetTable<T>().InsertOnSubmit(entity);
}
public void InsertAllOnSubmit<T>(IEnumerable<T> entities) where T : class
{
Db.GetTable<T>().InsertAllOnSubmit(entities);
}
public void SubmitChanges()
{
try
{
Db.SubmitChanges();
}
catch (Exception ex)
{
new ErrorRepository().addError(ex);
}
}
public IEnumerable<TResult> ExecuteQuery<TResult>(string query, params object[] parameters)
{
return Db.ExecuteQuery<TResult>(query, parameters);
}
public DbConnection Connection()
{
return Db.Connection;
}
}
}
@Lechus
Copy link

Lechus commented Mar 7, 2017

@bradoyler: will this work with stored procedures?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment