Invalid object name 'dbo.UserRoles'

asp.net-mvc-4 entity-framework sql

Question

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

1
5
8/19/2015 3:52:07 PM

Popular Answer

The problem was unfortunately very simple - as i have 2 areas - main and administrator and respectively i have 2 types of data connection, i have only 1 connection string in webconfig. after i added second line for admin context and all works thanks for attention ) so the problem was incomplete (misconfiguration) in webconfig

5
9/11/2013 5:31:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow