如何使用 EF 和 MVC 3 连接到 SQL Server 2008 R2 [英] How to Connect to SQL Server 2008 R2 Using EF and MVC 3

查看:16
本文介绍了如何使用 EF 和 MVC 3 连接到 SQL Server 2008 R2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想学习 MVC 3 并遵循 Wrox 的一本书.在我尝试执行一个小练习之前,一切都很好.我收到一个非常常见的错误.我已经尝试了一切,但找不到问题所在.谁能帮帮我.

I am simply trying to learn MVC 3 and following a book from Wrox. Things were fine until I tried to execute a small exercise. I am getting an error which is very common. I have tried everything but could't find what the problem is. Can somebody help me out.

我的配置.

  1. 先安装VS201,然后用WebPlatForm Installer安装SP1.哪个确实在我的机器上安装了 SP1 并安装了 MVC3 模板和框架.到目前为止一切顺利.

  1. installed VS201 and then used WebPlatForm Installer to install SP1. Which did installed SP1 and installed MVC3 templates and framework as well on my machine. So far so good.

之后我又安装了 SQL Server 2008 R2 开发者版,到目前为止还不错.

After that I installed SQL Server 2008 R2 Developer Edition, again so far so good.

我一步一步地练习,发现一个错误,这对我来说是一场噩梦.错误如下所述.

I followed step by step the exercise and found an error which is becoming a nightmare for me. the error is mentioned below.

System.Data.ProviderIncompatibleException was unhandled by user code
  Message=The provider did not return a ProviderManifestToken string.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
       at System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
       at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
       at System.Data.Entity.Internal.InternalContext.Initialize()
       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.Include(String path)
       at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)
       at System.Data.Entity.DbExtensions.Include[T](IQueryable`1 source, String path)
       at System.Data.Entity.DbExtensions.Include[T,TProperty](IQueryable`1 source, Expression`1 path)
       at MvcMusicStore.Controllers.StoreManagerController.Index() in c:usersukdocumentsvisual studio 2010ProjectsMvcMusicStoreMvcMusicStoreControllersStoreManagerController.cs:line 21
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: System.Data.SqlClient.SqlException
       Message=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)
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=20
       LineNumber=0
       Number=-1
       Server=""
       State=0
       StackTrace:
            at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
            at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
            at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
            at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
            at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
            at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
            at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
            at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
            at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
            at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
            at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
            at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
            at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
            at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
            at System.Data.SqlClient.SqlConnection.Open()
            at System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act)
            at System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act)
            at System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
            at System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
       InnerException: 

作为解决方案.我已经检查了 SQL Server Browser 服务是否已启用.我还执行了 Microsoft 的 PortyQry.exe 以了解 SQL Server 是否响应.并收到以下回复.

As a solution. I have checked the SQL Server Browser Service is enabled. Also I executed the PortyQry.exe from Microsoft to find out if SQL Server is responding. and received the below response.

Attempting to resolve name to IP address...


Name resolved to x.x.x.x

querying...

UDP port 1434 (ms-sql-m service): LISTENING or

Sending SQL Server query to UDP port 1434...

Server's response:

ServerName MVC3Machine
InstanceName MSSQLSERVER
IsClustered No
Version 10.50.1600.1
tcp 1433

 ♦  ♦

==== End of SQL Server query response ====

这里也是连接字符串

<add name="MusicStoreDB" connectionString="Server=(local); Database=MusicStore; Trusted_Connection=true; Integrated Security=True" providerName="System.Data.SqlClient" />

我没有使用任何数据库来构建我的模型.我正在尝试使用 EF 的 Code First 方法.

I am not using any database to build my Model. I am trying to use Code First approach of EF.

编辑 2:

using System.Data.Entity;

namespace MvcMusicStore.Models
{
    public class MvcMusicStoreContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<MvcMusicStore.Models.MvcMusicStoreContext>());

        public DbSet<Album> Albums { get; set; }

        public DbSet<Genre> Genres { get; set; }

        public DbSet<Artist> Artists { get; set; }
    }
}

任何人都可以建议我尝试一下...

Anybody can suggest me something to try...

谢谢

推荐答案

默认情况下,EFCF 将尝试在本地 ./SQLEXPRESS 上从您的模型创建数据库 如果您想在 web.config 中指定不同的连接字符串您必须在数据库上下文的构造函数中告诉 EF 您的连接字符串的名称,如下所示:

By default, EFCF will try to make a database from your model on your local ./SQLEXPRESS If you want to specify a different connection string in your web.config you have to tell EF the name of your connection string in the constructor of your database context like below:

public class MvcMusicStoreContext: DbContext 
{
    //Add the name of your database connection to the base DbContext calss
    public MvcMusicStoreContext() : base("MusicStoreDB")
    {}

    public DbSet<Album> Albums { get; set; }

    public DbSet<Genre> Genres { get; set; }

    public DbSet<Artist> Artists { get; set; }
}

你的连接字符串:

<add name="MusicStoreDB" connectionString="Data Source=localhost;Initial Catalog=MusicStoreDB;Integrated Security=True" providerName="System.Data.SqlClient"/>

这篇关于如何使用 EF 和 MVC 3 连接到 SQL Server 2008 R2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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