Home

LINQPadDbConnection vs. SqlConnection

I'm using Entity Framework Model First and LinqPad is fine by reading in the Model Entities with a successful connection to the repository dll. That's fine for design...then I try to execute the query. When it hits the first line of code that actually pulls data,
(int c = query.Where(d => d.DayOfWeek.StartsWith(dm) & d.DAY_ID < 20121120).Count();) ...
I get an error : InvalidCastException. Unable to cast object of type 'LINQPad.LINQPadDbConnection' to type 'System.Data.SqlClient.SqlConnection'.
Message Unable to cast object of type 'LINQPad.LINQPadDbConnection' to type 'System.Data.SqlClient.SqlConnection'. If I attach LinqPad to my VisualStudio and run the code in LinqPad, I can confirm that when the dbContext is initialized, that the correct connection string is read from the config file. So it knows "where" the db is. I think I'm really close, to having LinqPad use my dbContext, but finally hit a wall. Thanks for any advice on this.
Donna

Comments

  • edited November 2012
    Have you looked, in the exception stack trace, as to where the InvalidCastException is actually occuring? It seems to me a bug that one should assume that the connection is of type SqlException. Any IDbConnection should do.

    LINQPad re-assigns the connection in order to populate the SQL log.
  • Looks like the exception is occurring in System.Linq.Queryable.Count ( at System.Linq.Queryable.Count[TSource](IQueryable`1 source) This query works fine in my repository method which feeds a bar chart, So I know it returns data. However, I removed the .Count in my expression within LinqPad, and it works. So it's specific with .Count. It doesn't have anything to do with getting to the data.
  • If you create a simple model from scratch and query it in the same fashion, do you get the same error?
  • edited October 2013
    I've recently run into this issue after upgrading to EF6 /w v4.47.02.

    Code:

    IDbContext ctx = this;
    IUnitOfWork uow = new UnitOfWork(ctx);
    var userRepo = uow.Repository<AppUser>();
    userRepo.Any(u => u.ActiveState == EntityActiveState.Active).Dump("Any active users?");

    InvalidCastException: Unable to cast object of type 'LINQPad.Internal.LINQPadDbConnection' to type 'System.Data.SqlClient.SqlConnection'

    at System.Data.SqlClient.SqlCommand.set_DbConnection(DbConnection value)
    at System.Data.Common.DbCommand.set_Connection(DbConnection value)
    at System.Data.Entity.Internal.InterceptableDbCommand.set_DbConnection(DbConnection value)
    at System.Data.Common.DbCommand.set_Connection(DbConnection value)
    at System.Data.Entity.Core.Common.Utils.CommandHelper.SetStoreProviderCommandState(EntityCommand entityCommand, EntityTransaction entityTransaction, DbCommand storeProviderCommand)
    at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.PrepareEntityCommandBeforeExecution(EntityCommand entityCommand)
    at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
    at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.b__a()
    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.b__9()
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
    at System.Data.Entity.Core.Objects.ObjectQuery`1..GetEnumerator>b__0()
    at System.Lazy`1.CreateValue()
    at System.Lazy`1.LazyInitValue()
    at System.Lazy`1.get_Value()
    at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
    at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
    at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.b__3[TResult](IEnumerable`1 sequence)
    at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
    at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
    at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
    at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
    at System.Data.Entity.Migrations.History.HistoryRepository.QueryExists(String contextKey)
    at System.Data.Entity.Migrations.History.HistoryRepository.Exists(String contextKey)
    at System.Data.Entity.Migrations.History.HistoryRepository.GetLastModel(String& migrationId, String contextKey)
    at System.Data.Entity.Migrations.History.HistoryRepository.GetLastModel()
    at System.Data.Entity.Internal.InternalContext.QueryForModel()
    at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata)
    at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)
    at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
    at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse`1.b__d()
    at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
    at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
    at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)
    at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
    at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
    at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
    at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
    at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
    at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
    at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
    at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
    at HC.Infrastructure.Data.Repository`1.Any(Func`2 filter)
  • A beta has now been uploaded that should fix this:
    www.linqpad.net/beta.aspx

    Let me know how you get along.

    Cheers
    Joe
  • That did the trick for me. The new beta also restored my SQL tab (was no longer displaying the executed SQL query). All is working now

    Thanks Joe!!
  • We have just upgraded an ObjectContext database first model from EF 4 to 6.1.3 and are now encountering this issue when our LINQPad scripts call into code that creates an instance of the model outside of LINQPad and runs a ToList(). This code previously worked prior to the EF upgrade.

    We were running the latest version of LP v5 Premium and can also confirm the current Beta 5.22 is having the same issue.

    We have recreated connections and used fresh queries to try and eliminate anythign in that area.

    Any guidance on possible work around or if this is possibly a regression of the original issue would be appreciated. I can't see anyway to disable the SQL tab within LINQPad however I assume that is what is causing the issue from reading the above.

    Regards Chad

    {"Unable to cast object of type 'LINQPad.Data.Internal.LINQPadDbConnection' to type 'System.Data.SqlClient.SqlConnection'."}

    StackTrace
    at System.Data.SqlClient.SqlCommand.set_DbConnection(DbConnection value)
    at System.Data.Entity.Core.Common.Utils.CommandHelper.SetStoreProviderCommandState(EntityCommand entityCommand, EntityTransaction entityTransaction, DbCommand storeProviderCommand)
    at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.PrepareEntityCommandBeforeExecution(EntityCommand entityCommand)
    at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
    at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.b__5()
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
    at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
    at System.Data.Entity.Core.Objects.ObjectQuery`1..GetEnumerator>b__0()
    at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
    at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
    at Halo.Integration.QA.Engine.ExecuteRules()
    at UserQuery.Main() in C:\Users\chad.campling\AppData\Local\Temp\LINQPad5\_uocgkckn\query_ojwlnt.cs:line 48
    at LINQPad.ExecutionModel.ClrQueryRunner.Run()
    at LINQPad.ExecutionModel.Server.RunQuery(QueryRunner runner)
    at LINQPad.ExecutionModel.Server.StartQuery(QueryRunner runner)
    at LINQPad.ExecutionModel.Server.<>c__DisplayClass152_0.b__0()
    at LINQPad.ExecutionModel.Server.SingleThreadExecuter.Work()
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
Sign In or Register to comment.