Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I write an extension method for System.Data.Linq.Table<T>?

I wanted to write this small, trivial extension method for some throwaway test / console app and I haven't been able to figure out how to get the method signature right. I'm looking to add this to every System.Data.Linq.Table that I have and I want it to take an instance of type T as a parameter.

Here's what I have so far that doesn't compile

public static void InsertAndSubmit<T>(this System.Data.Linq.Table<T> tbl, T element)
{
    tbl.InsertOnSubmit(element);
    tbl.Context.SubmitChanges();
}

The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table'

like image 340
Allen Rice Avatar asked Jan 19 '23 09:01

Allen Rice


2 Answers

Try this:

public static void InsertAndSubmit<T>(this System.Data.Linq.Table<T> tbl, T element)
    where T : class
{
    tbl.InsertOnSubmit(element);
    tbl.Context.SubmitChanges();
}

You need to constrain the type of T to be a reference type (class) in order for this to work.

If you look at Table<TEntity>'s documentation you will notice this same type constraint on TEntity of class. So for your T to be compatible with TEntity it must meet the same constraints.

like image 186
Joshua Rodgers Avatar answered Jan 20 '23 23:01

Joshua Rodgers


You need to specify that you will use only refernece types in your T. Try:

public static void InsertAndSubmit<T>(this System.Data.Linq.Table<T> tbl, T element) 
    where T : class
{
    tbl.InsertOnSubmit(element);
    tbl.Context.SubmitChanges();
}
like image 24
Samich Avatar answered Jan 20 '23 22:01

Samich