【问题标题】:code first entity framework does can't connect to database代码优先实体框架确实无法连接到数据库
【发布时间】:2014-05-24 23:25:42
【问题描述】:

我知道这个问题必须先回答,但我找不到我的情况的解决方案。 我在 Visual Studio 2013 中创建了一个基于服务的数据库,我想连接到这个数据库。 我创建了 dbSet,继承自 DbContext 的类并添加了实体框架引用,一切都很好,除了连接字符串

<connectionStrings>
<add name ="master" connectionString="Data Source=(localdb)\v11.0;
                      AttachDbFilename=c:\users\reda\documents\visual studio 2013\Projects\Testing new things\Testing new things\master.mdf;
                      Integrated Security=True;"/>  </connectionStrings>

当我运行我的程序时,我得到一个 Data.Entity.Core.ProviderIncompatibleException 异常;这意味着它无法访问数据库,我哪里错了?

顺便说一句,还有其他解决方案可以使用本地数据库吗?

错误信息是:

    Unhandled Exception: System.Data.Entity.Core.ProviderIncompatibleException: An e
rror occurred accessing the database. This usually means that the connection to
the database failed. Check that the connection string is correct and that the ap
propriate DbContext constructor is being used to specify it or find it in the ap
plication's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for i
nformation on DbContext and connections. See the inner exception for details of
the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The pro
vider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.
SqlException: A network-related or instance-specific error occurred while establ
ishing a connection to SQL Server. The server was not found or was not accessibl
e. Verify that the instance name is correct and that SQL Server is configured to
 allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local
Database Runtime error occurred. The specified LocalDB instance does not exist.
)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception
, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObj
ect stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternal
ConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Bool
ean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFa
ilover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSn
iOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirect
edUserInstance, SqlConnectionString connectionOptions, SqlCredential credential,
 TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTime
r timeout, SqlConnectionString connectionOptions, SqlCredential credential, Stri
ng newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdent
ity identity, SqlConnectionString connectionOptions, SqlCredential credential, O
bject providerInfo, String newPassword, SecureString newSecurePassword, Boolean
redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData r
econnectSessionData)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOp
tions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConn
ectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)

   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConn
ectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConne
ctionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owning
Object, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection o
wningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection
)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection ow
ningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean o
nlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& co
nnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection ow
ningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbCon
nectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
 owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions
, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(Db
Connection outerConnection, DbConnectionFactory connectionFactory, TaskCompletio
nSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
 outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1
retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 re
try)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Ope
n>b__38(DbConnection t, DbConnectionInterceptionContext c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispat
ch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TIntercepti
onContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open
(DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass31.<Usin
gConnection>b__2f()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass
1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](
Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action op
eration)
   at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnect
ion sqlConnection, Action`1 act)
   at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbC
onnection sqlConnection, Action`1 act)
   at System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToke
n(DbConnection connection)
   at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken
(DbConnection connection)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken
(DbConnection connection)
   at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManif
estTokenChecked(DbProviderServices providerServices, DbConnection connection)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManif
estTokenChecked(DbProviderServices providerServices, DbConnection connection)
   at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__Displa
yClass1.<ResolveManifestToken>b__0(Tuple`3 k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Fu
nc`2 valueFactory)
   at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveMani
festToken(DbConnection connection)
   at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConn
ection connection, DbProviderManifest& providerManifest)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalCo
ntext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   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.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, Ent
ityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   at System.Data.Entity.DbSet`1.Add(TEntity entity)
   at Testing_new_things.Program.Main(String[] args) in c:\Users\Reda\Documents\
Visual Studio 2013\Projects\Testing new things\Testing new things\Program.cs:lin
e 19
Press any key to continue . . .

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您的连接字符串缺少提供程序信息。改成这个

    <add name ="master" connectionString="Data Source=(localdb)\v11.0;
                      AttachDbFilename=c:\users\reda\documents\visual studio 2013\Projects\Testing new things\Testing new things\master.mdf;
                      Integrated Security=True;"
    providerName="System.Data.SqlClient"/>
    

    【讨论】:

    • 您也可能在实际连接字符串中缺少Initial Catalog 属性。
    • 我之前添加了 providerName 但没有用,还有初始目录。并且不起作用
    • 那个文件名存在吗?
    • 是的,通常当我首先使用代码时,它应该生成一个 localdb,但它不会
    • 您是否将数据库文件表单移动到默认位置?它通常位于项目的App_Data 文件夹中,这意味着完整路径应为c:\users\reda\documents\visual studio 2013\Projects\Testing new things\Testing new things\App_Data\master.mdf
    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 2012-03-03
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多