使用connectionString访问现有表

时间:2014-07-02 14:27:04

标签: c# sql-server asp.net-mvc entity connection-string

我正在编写一个Web应用程序,它将访问/更新数据库中的几个现有表。目前,我试图在SQL Express上访问本地版本的数据库以进行测试,但在搜索完成后无法正确设置连接。我的web.config文件当前的连接字符串设置如下:

<add name="ContractDBContext" 
     connectionString="Data Source=SBUWMPB01FHSM\SQLEXPRESS;
                       Initial Catalog=12-2013 Derivative TrackingSQL;
                       Integrated Security=True" 
     providerName="System.Data.SqlClient" />

这是为数据库表建模的类的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ForeignExchange.Models
{
    [Table("AccountingData")]
    public class Contract
    {
        [Key][Required]
        public int TKRContractID { get; set; }
        public int AsOfMonth { get; set; }
        public int AsOfQuarter { get; set; }
        public int ASOfYear { get; set; }
        public double CurrentMoFMVChg { get; set; }
        public double LTDFMVChg { get; set; }
        public double AccumulatedOCI { get; set; }
        public double AccumulatedDerivAsset { get; set; }
        public double AccumulatedPL { get; set; }
        public double AccumulatedFAS5 { get; set; }
        public double HistoricalSpotRate { get; set; }
        public double HistoricalHedgedRate { get; set; }
    }
    [Table("AccountingData")]
    public class ContractDBContext : DbContext
    {
        public DbSet<Contract> Contracts { get; set; }
    }
}

在编写上面给出的两段代码之后,我使用“添加控制器”自动对话框来生成CRUD .cshtml页面和名为ContractsController的控制器。一旦我运行代码并尝试访问应该显示该表的生成的索引页面,我就会在行上出现以下错误

return View(db.Contracts.ToList())

EntityCommandExecutionExcception
An error occurred while executing the command definition.
System.Data.EntityCommandExecutionException was unhandled by user code
  HResult=-2146232004
  Message=An error occurred while executing the command definition. See the inner exception for details.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
       at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
       at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
       at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator()
       at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
       at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at ForeignExchange.Controllers.ContractsController.Index() in C:\Users\stonejo\documents\visual studio 2010\Projects\ForeignExchange\ForeignExchange\Controllers\ContractsController.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.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
       at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
  InnerException: System.Data.SqlClient.SqlException
       HResult=-2146232060
       Message=Invalid column name 'AccumulatedFAS5'.
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=16
       LineNumber=11
       Number=207
       Procedure=""
       Server=SBUWMPB01FHSM\SQLEXPRESS
       State=1
       StackTrace:
            at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
            at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
            at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
            at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
            at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
            at System.Data.SqlClient.SqlDataReader.get_MetaData()
            at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
            at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       InnerException: 

连接字符串和基于网络的应用程序对我来说是全新的,所以我感谢有人可以为此提供的任何帮助。感谢您抽出宝贵时间阅读我的问题。

1 个答案:

答案 0 :(得分:1)

尝试使用visual studio转到数据源,添加新数据源并让向导弄明白。如果需要,打开一个新的Visual Studio实例,创建一个新的解决方案/项目,只需获得结果,然后将其复制/粘贴到原始解决方案中。