Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linqpad & EF5 Code First

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?

like image 559
dandcg Avatar asked Aug 29 '12 16:08

dandcg


2 Answers

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 });

?

like image 197
Joe Albahari Avatar answered Oct 09 '22 21:10

Joe Albahari


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});
like image 40
Justin Holzer Avatar answered Oct 09 '22 21:10

Justin Holzer