Estou iniciando hoje com o Entity-FrameWork mas me deparei com um problema que acredito ser simples, mas não consegui achar a resposta em lugar algum, talvez por não saber bem ao certo pelo o que procurar.
O código é o seguinte:
using(var db = new CadastroContext())
{
var query = from c in db.Cadastros select c;
foreach(Cadastro ca in query)
{
Debug.WriteLine(ca.CadastroID +" :: "+ca.Familiares.Count); //O erro sempre acontece quando tenta acessar a List
}
}
Rodava normalmente até que eu direcionei o Context para um localdb
public class CadastroContext : DbContext
{
/*
public CadastroContext() : base()
{
}
*/
public CadastroContext()
: base(@"Data Source=(localdb)\v11.0;AttachDbFilename=D:\GitHub\SaneamentoBR\GerenciadorPesquisa\GerenciadorPesquisa\PesquisaSorriso.mdf;Initial Catalog=PesquisaSorriso;Integrated Security=True")
{
}
public DbSet<Cadastro> Cadastros { get; set; }
public DbSet<Familiar> Familiares { get; set; }
public DbSet<Telefone> Telefones { get; set; }
}
Agora ele sempre gera um erro, e o único registro que ele consegue acessar a Lista é o ultimo. E quando eu adiciono outro elementro, apenas esse ultimo consegue acessar novamente a lista repetindo esse ciclo.
O stacktrace gerado é esse:
System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Exceção não tratada</Description><AppDomain>GerenciadorPesquisa.vshost.exe</AppDomain><Exception><ExceptionType>System.Data.Entity.Core.EntityCommandExecutionException, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>An error occurred while executing the command definition. See the inner exception for details.</Message><StackTrace> em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
em System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
em System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6()
em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
em System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5()
em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
em System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
em System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()
em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.&lt;&gt;c__DisplayClass7`2.&lt;GetInterceptorDelegate&gt;b__1(TProxy proxy, TItem item)
em System.Data.Entity.DynamicProxies.Cadastro_875C0EB92CA3613483BF1786024F3D0495A118E3EA8FBBD34C417E9919F975D3.get_Familiares()
em GerenciadorPesquisa.Program.Main() na d:\GitHub\SaneamentoBR\GerenciadorPesquisa\GerenciadorPesquisa\Program.cs:linha 78
em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
em System.Threading.ThreadHelper.ThreadStart()</StackTrace><ExceptionString>System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---&gt; System.InvalidOperationException: Já existe um DataReader aberto associado a este Command que deve ser fechado primeiro.
em System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
em System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean asyncWrite)
em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
em System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
em System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
em System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;Reader&gt;b__c(DbCommand t, DbCommandInterceptionContext`1 c)
em System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
em System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
em System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
--- Fim do rastreamento de pilha de exceções internas ---
em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
em System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
em System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6()
em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
em System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5()
em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
em System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
em System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()
em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.&lt;&gt;c__DisplayClass7`2.&lt;GetInterceptorDelegate&gt;b__1(TProxy proxy, TItem item)
em System.Data.Entity.DynamicProxies.Cadastro_875C0EB92CA3613483BF1786024F3D0495A118E3EA8FBBD34C417E9919F975D3.get_Familiares()
em GerenciadorPesquisa.Program.Main() na d:\GitHub\SaneamentoBR\GerenciadorPesquisa\GerenciadorPesquisa\Program.cs:linha 78
em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
em System.Threading.ThreadHelper.ThreadStart()</ExceptionString><InnerException><ExceptionType>System.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Já existe um DataReader aberto associado a este Command que deve ser fechado primeiro.</Message><StackTrace> em System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
em System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean asyncWrite)
em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
em System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
em System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
em System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;Reader&gt;b__c(DbCommand t, DbCommandInterceptionContext`1 c)
em System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
em System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
em System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)</StackTrace><ExceptionString>System.InvalidOperationException: Já existe um DataReader aberto associado a este Command que deve ser fechado primeiro.
em System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
em System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean asyncWrite)
em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
em System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
em System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
em System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;Reader&gt;b__c(DbCommand t, DbCommandInterceptionContext`1 c)
em System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
em System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
em System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
em System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)</ExceptionString></InnerException></Exception></TraceRecord>
Já tentei apagar todas as tabelas, mas nada resolveu.
@update Adicionei um .ToList(), no final da query e aparentemente resolveu, mas ainda não entendi bem o por que, vou deixar a pergunta aberta caso alguém saiba explicar o que aconteceu, pode ser útil...
using(var db = new CadastroContext())
{
var query = (from c in db.Cadastros select c).ToList();
foreach(Cadastro ca in query)
{
Debug.WriteLine(ca.CadastroID +" :: "+ca.Familiares.Count);
}
}