指着EF到数据库时的POCO文件是在一个单独的项目 [英] Pointing EF to a database when the POCO files are in a seperate project

查看:149
本文介绍了指着EF到数据库时的POCO文件是在一个单独的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在这3个项目单ASP.Net解决方案。数据访问层(DAL)包含code第一CS文件我的数据库的API项目,UI项目。我已经安装了API的web.config文件以指向Azure中我的测试数据库,我已经安装了实体框架到API和DAL两者。

当我去运行程序包管理器控制台使用更新数据库我的错误我的第一个迁移无迁移配置类型被发现大会API中于是我跑启用的迁移,但得到的错误没有上下文类型被装配API中发现。然后,我设置缺省项目DAL和网络连接错误运行更新,数据库,并出现了错误。我可以进入MSSQL Studio并从我的连接字符串使用相同的连接数据和登录就好了。所以我在做什么错了?怎样才可以有一个独立的DAL项目,但仍然一切工作的?

下面是完整的错误,我得到


  

PM>更新数据库指定-Verbose'标志来查看SQL
  语句被应用到目标数据库。
  System.Data.SqlClient.SqlException(0x80131904):与网络相关的或
  在建立连接时出现特定实例的错误
  SQL Server中。服务器未找到或无法访问。校验
  实例名称是否正确,以及SQL Server配置
  允许远程连接。 (提供者:SQL网络接口,error:26
   - 在System.Data.SqlClient.SqlInternalConnection.OnError错误定位服务器/实例指定)(SQLEXCEPTION
  例外,布尔breakConnection,行动 1 wrapCloseInAction)在
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
  stateObj,布尔callerHasConnectionLock,布尔asyncClose)在
  System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
  SqlInternalConnectionTds connHandler,布尔ignoreSniOpenTimeout,
  Int64的timerExpire,布尔加密,布尔trustServerCert,布尔
  integratedSecurity布尔withFailover)在
  System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
  serverInfo,字符串NEWPASSWORD,SecureString的newSecurePassword,
  布尔ignoreSniOpenTimeout,TimeoutTimer超时,布尔
  withFailover)在
  System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
  serverInfo,字符串NEWPASSWORD,SecureString的newSecurePassword,
  布尔redirectedUserInstance,SqlConnectionString connectionOptions,
  SqlCredential凭证,TimeoutTimer超时)在
  System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
  超时,SqlConnectionString connectionOptions,SqlCredential
  凭据,字符串NEWPASSWORD,SecureString的newSecurePassword,
  布尔redirectedUserInstance)在
  System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
  身份,SqlConnectionString connectionOptions,SqlCredential
  凭据,对象providerInfo,字符串NEWPASSWORD,SecureString的
  newSecurePassword,布尔redirectedUserInstance,SqlConnectionString
  userConnectionOptions,SessionData reconnectSessionData)在
  System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
  选项​​,DbConnectionPoolKey poolKey,对象poolGroupProviderInfo,
  池类DBConnectionPool,的DbConnection owningConnection,
  DbConnectionOptions USEROPTIONS)在
  System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(类DBConnectionPool
  池的DbConnection owningObject,DbConnectionOptions选项,
  DbConnectionPoolKey poolKey,DbConnectionOptions USEROPTIONS)在
  System.Data.ProviderBase.DbConnectionPool.CreateObject(的DbConnection
  owningObject,DbConnectionOptions USEROPTIONS,DbConnectionInternal
  oldConnection)在
  System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(的DbConnection
  owningObject,DbConnectionOptions USEROPTIONS,DbConnectionInternal
  oldConnection)在
  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(的DbConnection
  owningObject,UInt32的waitForMultipleObjectsTimeout,布尔
  allowCreate,布尔onlyOneCheckConnection,DbConnectionOptions
  USEROPTIONS,DbConnectionInternal&安培;连接)在
  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(的DbConnection
  owningObject,TaskCompletionSource
1重试,DbConnectionOptions
  USEROPTIONS,DbConnectionInternal&安培;连接)在
  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(的DbConnection
  owningConnection,TaskCompletionSource 1重试,DbConnectionOptions
  USEROPTIONS,DbConnectionInternal oldConnection,DbConnectionInternal&安培;
  连接)在
  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(的DbConnection
  outerConnection,DbConnectionFactory connectionFactory的,
  TaskCompletionSource
1重试,DbConnectionOptions USEROPTIONS)在
  System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(的DbConnection
  outerConnection,DbConnectionFactory connectionFactory的,
  TaskCompletionSource 1重试,DbConnectionOptions USEROPTIONS)在
  System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource
1
  重试)在
  System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource 1
  重试)在System.Data.SqlClient.SqlConnection.Open()在
  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher<开和GT; b__36(的DbConnection
  T,DbConnectionInterceptionContext三)
  System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget
  目标,行动 2的操作,TInterceptionContext interceptionContext,
  操作
3执行,行动 3执行)在
  System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(的DbConnection
  连接,DbInterceptionContext interceptionContext)在
  System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
  在
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
  在
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute [TResult](Func键
1
  操作)的
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(动作
  操作)的
  System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(的DbConnection
  SqlConnection的,动作 1的行为)的
  System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(的DbConnection
  SqlConnection的,动作
1的行为)的
  System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(可空 1
  的CommandTimeout,SqlConnection的的DbConnection,字符串
  createDatabaseScript)在
  System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(的DbConnection
  连接,可为空
1的CommandTimeout,StoreItemCollection
  storeItemCollection)在
  System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(的DbConnection
  连接,Nullable`1的CommandTimeout,StoreItemCollection
  storeItemCollection)在
  System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()在
  System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(的DbConnection
  连接)在
  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(动作
  mustSucceedToKeepDatabase)在
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(动作
  mustSucceedToKeepDatabase)在
  System.Data.Entity.Migrations.DbMigrator.Update(字符串
  targetMigration)在
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(字符串
  targetMigration)在
  System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
  在System.AppDomain.DoCallBack(CrossAppDomainDelegate
  callBackDelegate)在
  System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)结果
  在System.Data.Entity.Migrations.Design.ToolingFacade.Run(跑垒员
  亚军)在
  System.Data.Entity.Migrations.Design.ToolingFacade.Update(字符串
  targetMigration,布尔力)在
  System.Data.Entity.Migrations.UpdateDatabaseCommand&LT;> c__DisplayClass2&LT; .ctor> b__0()
  在
  System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(动作
  命令)ClientConnectionId:00000000-0000-0000-0000-000000000000错误
  号:-1,状态:0,等级:20与网络相关的或特定于实例
  而与SQL Server建立连接时出现错误。该
  服务器未找到或无法访问。验证实例
  名称正确,并且该SQL服务器被配置为允许远程
  连接。 (提供者:SQL网络接口,错误:26 - 错误
  定位服务器/实例指定)



解决方案

好像你已经交换了一些东西。这应该可以解决您的情况:


  • 安装实体框架的项目,你需要它(DAL和API)。

  • 创建一个的DbContext 在DAL继承类。

  • 安装迁移(启用的迁移)的DAL。

  • 把你的连接字符串中都DAL的的 App.Config中的和API的的Web.Config

  • 设置DAL作为默认的项目。

  • 使用更新数据库执行迁移,选择性呼叫添加迁移mymigration如果 AutomaticMigrationsEnabled

您还可以在您的API项目迁移安装并使用启用的迁移-contextassemblynameDAL来保持你的DbContext在DAL项目。这将允许您只使用API​​的配置文件,你就不必把它复制到DAL项目也是如此。随后,您可以拨打更新数据库从现在起迁移此处安装API项目。

现在这里就是你出了错:你在DAL安装迁移(这意味着你必须设置DAL作为启动项目),但你只把在ConnectionString中的API。被设置为启动将其配置文件加载 只有这个项目!

当你发布你的应用程序将使用你提供的API,使一切都很好的连接字符串:您不必在这一点上执行任何迁移。

I have a single ASP.Net solution with 3 projects in it. The Data Access Layer (DAL) that contains the code first CS files for my database, the API project, and the UI Project. I have setup the web.config file of the API to point to my test DB in Azure, I have installed Entity Framework into both the API and DAL.

When I go to run my first migration from the Package Manager Console using the UPDATE-DATABASE I get the error No migrations configuration type was found in the assembly API So then I run Enable-Migrations but get the error No context type was found in the assembly API. I then set the Default Project to the DAL and run the Update-Database and it errors out with a network connection error. I can go into MSSQL Studio and use the same connection data from my connection string and login just fine. So what am I doing wrong? How can I have a separate DAL project but still have everything working?

Here is the full error I get

PM> UPDATE-DATABASE Specify the '-Verbose' flag to view the SQL statements being applied to the target database. System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.Open() at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act) at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run() at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force) at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0() at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command) ClientConnectionId:00000000-0000-0000-0000-000000000000 Error Number:-1,State:0,Class:20 A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

解决方案

It seems like you've been switching some things up. This should fix your situation:

  • Install Entity-Framework in the projects you need it (DAL and API).
  • Create a DbContext inherited class in DAL.
  • Install Migrations (enable-migrations) in DAL.
  • Put your connection string in both DAL's App.Config and API's Web.Config.
  • Set DAL as your default project.
  • Execute a migration using update-database, optionally calling add-migration "mymigration" if AutomaticMigrationsEnabled is false.

You can also install Migrations in your API project and use enable-migrations -contextassemblyname "DAL" to keep your DbContext in the DAL project. This will allow you to just use the API's configuration file and you won't have to copy it to the DAL project as well. Subsequently you can call update-database from the API project since now Migrations is installed here.

Now here's where you went wrong: you installed Migrations in DAL (meaning you have to set DAL as your startup project) but you only put the connectionstring in API. Only the project that is set as startup will have its configuration file loaded!

When you publish your application it will use the connection string you provide in API so that's all good: you don't have to execute any migrations at that point.

这篇关于指着EF到数据库时的POCO文件是在一个单独的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆