9

Getting the following error when trying to run a query against a dbcontext assembly in Linqpad.

InvalidOperationException: The model backing the 'UserQuery' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

Having done a bit of reading it seems that:

Database.SetInitializer<DiaryAssistantContext>(null);

is needed. However this is already in my derived DbContext class.

Can anybody give me a pointer?

BNL
  • 7,085
  • 4
  • 27
  • 32
dandcg
  • 442
  • 4
  • 16

2 Answers2

10

LINQPad subclasses your typed data context so you can run queries without referencing the instance. Maybe the SetInitializer method needs the subclassed type.

What happens if you replace this code:

Database.SetInitializer<DiaryAssistantContext>(null);

with this:

typeof (Database).GetMethod ("SetInitializer").MakeGenericMethod (GetType()).Invoke (null, new object[] { null });

?

Joe Albahari
  • 30,118
  • 7
  • 80
  • 91
  • I have added your suggested line to the constructor of the dbcontext derived class and it works perfectly. I'm not sure fully understand why though. – dandcg Aug 30 '12 at 09:49
  • 1
    GetType() is virtual, so it's equivalent to calling Database.SetInitializer(null); when run in LINQPad – Joe Albahari Aug 31 '12 at 01:37
6

While an answer has already been accepted, in my case I wanted a solution that was a little more compile-time friendly. The following solution is similar to the example in the accepted answer that uses reflection, but will provide a little extra compile-time checking:

Expression<Action> setInitializerExpression = () => Database.SetInitializer<MyContext>(null);
var setInitializerCall = (MethodCallExpression) setInitializerExpression.Body;
var setInitializerMethodInfo =
    setInitializerCall.Method.GetGenericMethodDefinition().MakeGenericMethod(GetType());
setInitializerMethodInfo.Invoke(null, new object[] {null});
Justin Holzer
  • 2,326
  • 2
  • 22
  • 22