5

I am getting this error: [SqlException (0x80131904): Invalid object name 'dbo.UserRoles'.], but I can't catch where error is. I can retrieve other data from other tables, but not this.

conditions are:

connection string in web.config:

<add name="myStoreConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\myStore.mdf';Integrated Security=True" providerName="System.Data.SqlClient" />

context:

public class AdminMyStoreConnection : DbContext
    {
        public DbSet<UserRole> UserRoles { get; set; }
    }

sql script to create database:

CREATE TABLE [dbo].[UserRoles] (
    [RoleId]   INT            IDENTITY (1, 1) NOT NULL,
    [RoleName] NVARCHAR (256) NOT NULL,
    PRIMARY KEY CLUSTERED ([RoleId] ASC),
    UNIQUE NONCLUSTERED ([RoleName] ASC)
);

model:

[Table("UserRoles")]
public class UserRole
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}

controller with index view:

private UsersContext db = new UsersContext();
public ActionResult Index()
{
    return View(db.Customers.ToList());
}

view:

@using myStore.Helpers
@model IEnumerable<myStore.Areas.Administrator.Models.UserRole>

@{
    ViewBag.Title = "Roles management";
}

<h2>Roles management</h2>
<div class="admin-container">
<div class="bcontrol">
    <a href="@Url.Action("Create", "Roles")" class="btn btn-large btn-primary"><i class="icon-plus-sign"></i>&nbsp;Create New Entry</a>
</div>

@{
    var grid = new WebGrid(Model, defaultSort: "RoleId", canSort:true, canPage: true, rowsPerPage:20);
}

@grid.GetHtml(
    tableStyle: "tadmin",
    alternatingRowStyle: "alt",
    selectedRowStyle: "selected-row",
    columns:
        grid.Columns(
            grid.Column("RoleId",
                        header: "ID " + Html.SortDirection(ref grid, "RoleId"),
                        style: "tadmin-id"),

            grid.Column("RoleName",
                        header: "Role Name " + Html.SortDirection(ref grid, "RoleName"),
                        format: @<text><a href="@Url.Action("Details", "Roles", new { id = item.RoleId })" >@item.RoleName</a></text>),

            grid.Column("Control", style: "tadmin-control", canSort: false,
                        format:
                        @<text><a href="@Url.Action("Edit", "Roles", new { id = item.RoleId })" class="btn btn-large btn-primary"><i class="icon-edit"></i>&nbsp;Edit</a>
                        <a href="@Url.Action("Details", "Roles", new { id = item.RoleId })" class="btn btn-large btn-primary"><i class="icon-list"></i>&nbsp;Details</a>
                        <a href="@Url.Action("Delete", "Roles", new { id = item.RoleId })" class="btn btn-large btn-primary"><i class="icon-minus-sign"></i>&nbsp;Delete</a></text>)
                 )

        )</div>    

and error message:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.UserRoles'.

Source Error:


Line 19:         public ActionResult Index()
Line 20:         {
Line 21:             return View(db.UserRoles.ToList());
Line 22:         }
Line 23: 

and stack trace:

[SqlException (0x80131904): Invalid object name 'dbo.UserRoles'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296058 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10 System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +437

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +507
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +730
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +131
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() +36 System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +72
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +23
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() +40 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369 System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
myStore.Areas.Administrator.Controllers.RolesController.Index() in d:.projects\trains\myStore\myStore\Areas\Administrator\Controllers\RolesController.cs:21 lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.b__41() +28 System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult _) +10 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.b__33() +57 System.Web.Mvc.Async.<>c__DisplayClass4f.b__49() +223 System.Web.Mvc.Async.<>c__DisplayClass37.b__36(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.b__20() +24 System.Web.Mvc.Async.<>c__DisplayClass25.b__22(IAsyncResult asyncResult) +102 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57 System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

4

3 回答 3

5

不幸的是,这个问题非常简单——因为我有 2 个区域——主要和管理员,我分别有 2 种类型的数据连接,我在 webconfig 中只有 1 个连接字符串。在我为管理上下文添加第二行并且所有工作都感谢关注之后)所以问题在 webconfig 中不完整(配置错误)

于 2013-09-11T17:31:23.550 回答
2

这通常只是意味着配置问题

  • 也许真的没有这样的桌子
  • 也许桌子在那里,但不是 dbo 方案
  • 也许数据库区分大小写(确保两个表名拼写正确

资源

于 2013-09-10T18:17:36.313 回答
-1

如果不重新运行迁移,您table name的数据库必须与dbSet<> namedbContext 完全相同。(update-databse在声明 dbSet 之前运行可能会导致该问题)

像下面

在此处输入图像描述

于 2020-09-09T10:30:10.443 回答