I am using LINQPad to develop a new data access method. In the method, which performs a LINQ-to-SQL query against a table in MySchemaContext, I am using a parameter for which I am loading a default value from the same DataContext object using a static method.
When I call this static function in LINQPad (using the "C# Program" setting) - one that works fine when called from with an application, and that is public - I get a null reference exception on the line that assigns the return value of the static function to a variable. If I change the logic of the function, it works if I do not reference MySchemaContext (for instance, if I assemble the List by hand and return that), but throws the exception if I do reference MySchemaContext.
My guess is that this has something to do with the way LINQPad is connecting to my database - that the DataContext is not valid when the library function is called from LINQPad, and that the null reference exception is being thrown by GetTable<MyClassTable>
in the library. Is this a limitation of LINQPad, or is there something obvious I'm missing?
Here is a sample of the sort of function I'm having a problem with. The first part is the code in my library (which I am calling from the LINQPad query):
namespace MyLibrary
{
public class MyClass : MyClassTable
{
//There are reasons not to just add stuff to the partial class MyClassTable
//that aren't shown in this generic example
public int MyClassTemplateID {get; set;}
public int MyInt {get; set;}
public string MyString {get; set;}
public MyClass() {}
public MyClass(int myClassTemplateID, int myInt, string myString)
{
MyClassTemplateID = myClassTemplateID;
MyInt = myInt;
MyString = myString;
}
public static List<MyClass> GetMyClassesTemplate(int myClassTemplateID)
{
//MySchemaContext is a LINQ-to-SQL DataContext object, i.e., inherits from System.Data.Linq.DataContext
using (MySchemaContext myContext = new MySchemaContext())
{
return (from mct in myContext.GetTable<MyClassTable>().AsQueryable()
where mct.MyClassTemplateID == myClassTemplateID
select new MyClass
{
MyClassTemplateID = mct.MyClassTemplateID,
MyInt = mct.MyInt,
MyString = mct.MyString
}).ToList<MyClass>();
}
}
}
}
The library function works well in my application. This second part is in my LINQPad query, trying to call this same function:
/*
Call from LINQPad
MyLibrary.dll is in "Additional References," and MyLibrary is in "Additional Namespace Imports."
*/
void Main()
{
List<MyClass> myClassList = MyClass.GetMyClassesTemplate(1);
//get error "NullReferenceException: Object reference not set to an instance of an object.
//However, this exact line of code works fine in VisualStudio.
//Have correct connection string for MySchemaContext in LINQPad.exe.config and lprun.exe.config
}