Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a class Employee like:

C#
[Table("tlEmployee")]
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }

    }

Then created contet class for Employee like:

C#
public class EmployeeContext :DbContext
    {
        //establish a connection to the DB 
        public DbSet<employee> Employees { get; set; }
    }

Then created controller for the employee class like:

C#
public ActionResult Details(int id)
        {
            EmployeeContext employeeContext = new EmployeeContext();
            Employee employee= employeeContext.Employees.Single(emp=>emp.EmployeeId==id);

            return View(employee);
        }


This is my configuration in web.config:
HTML
<connectionstrings>
    <add name="EmployeeContext" connectionString="Server=.;database=sample;Initial Catalog=master;Integrated Security=true" providerName="System.Data.SqlClient" />



SQL table is:
SQL
[sample].[dbo].[tlEmployee]



Getting the below error:
SQL
Server Error in '/WebApplication2' Application.
Invalid object name 'dbo.tlEmployee'.
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.tlEmployee'.

Source Error: 


Line 15:         {
Line 16:             EmployeeContext employeeContext = new EmployeeContext();
Line 17:             Employee employee= employeeContext.Employees.Single(emp=>emp.EmployeeId==id);
Line 18: 
Line 19:             return View(employee);

Source File: C:\Users\Suni\documents\visual studio 2015\Projects\WebApplication2\WebApplication2\Controllers\EmployeeController.cs    Line: 17 

Stack Trace: 


[SqlException (0x80131904): Invalid object name 'dbo.tlEmployee'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +3277268
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +791
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4927
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +92
   System.Data.SqlClient.SqlDataReader.get_MetaData() +102
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +552
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +3114
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +554
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +98
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +307
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +505
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +37

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +126
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +1047
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +469
   System.Data.Entity.Core.Objects.<>c__DisplayClass7.<getresults>b__5() +205
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +238
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +349
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<t>.GetEnumerator>b__0() +30
   System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +37
   System.Linq.Enumerable.Single(IEnumerable`1 source) +240
   WebApplication2.Controllers.EmployeeController.Details(Int32 id) in C:\Users\Suni\documents\visual studio 2015\Projects\WebApplication2\WebApplication2\Controllers\EmployeeController.cs:17
   lambda_method(Closure , ControllerBase , Object[] ) +141
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +229
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<begininvokesynchronousactionmethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<invokeactionmethodfilterasynchronouslyrecursive>b__3d() +72
   System.Web.Mvc.Async.<>c__DisplayClass46.<invokeactionmethodfilterasynchronouslyrecursive>b__3f() +386
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass2b.<begininvokeaction>b__1c() +38
   System.Web.Mvc.Async.<>c__DisplayClass21.<begininvokeaction>b__1e(IAsyncResult asyncResult) +186
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<beginexecutecore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<beginprocessrequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.114.0


What I have tried:

I tried with un-installing and reinstalling the EntityFramewor, but no luck.
Verified the naming conventions but no use.

Can you please someone help me in resolving this issue?
Posted
Updated 26-Feb-19 21:52pm
v2
Comments
MadMyche 17-Aug-18 13:21pm    
Have you verified the table exists on the DB server
Member 13952856 17-Aug-18 13:49pm    
I have verified that table is present in DB

Quote:
[Table("tlEmployee")]


You've specified that your "database table" is named "tlEmployee".

The message says THAT table is not in the database.
 
Share this answer
 
Comments
Member 13952856 17-Aug-18 13:38pm    
but i have a table in databas:
SELECT TOP 1000 [EmployeeId]
,[Name]
,[Gender]
,[City]
FROM [sample].[dbo].[tlEmployee]
able to retrieve table
MadMyche 17-Aug-18 13:42pm    
Check your connection string and make sure you are pointing at the correct database on the server, and that the specified user is mapped to the correct schema.
Member 13952856 17-Aug-18 13:49pm    
This is my connection string
<connectionstrings>
<add name="EmployeeContext" connectionString="Server=.;database=sample;Initial Catalog=master;Integrated Security=true" providerName="System.Data.SqlClient" />
Vincent Maverick Durano 17-Aug-18 15:37pm    
Try this instead:

<add name="EmployeeContext" connectionString="Server=.;database=sample;Integrated Security=true" providerName="System.Data.SqlClient" />
Quote:
<connectionstrings>
<add name="EmployeeContext" connectionString="Server=.;database=sample;Initial Catalog=master;Integrated Security=true" providerName="System.Data.SqlClient" />


I'm guessing this is more of a connectionString issue then. In your connectionString you are setting a value master as Initial Catalog. The master database records all the system-level information for a SQL Server system. This means that you should avoid creating your database there. You should verify where your database sits in your SQL server and modify your connectionString accordingly.

Also, if you are using EF Core, then you can take a look at this article:
https://www.codeproject.com/Articles/1218427/Getting-Started-with-Entity-Framework-Core-Buildin
 
Share this answer
 
Comments
MadMyche 17-Aug-18 14:51pm    
If you look at his connection string..... it is populating the Initial Catalog as Master (which you suggested) and is also setting the "database" attribute to Sample.
I am surprised that nothing complained about using both the Initial Catalog and the Database alias for it
Vincent Maverick Durano 17-Aug-18 15:35pm    
Good catch. Well he can just remove the Initial Catalog attribute.
Everything looks good, the problem is in your Database string. I would suggest rewriting the Database not in the master, but in the regular database folder which should be the first one in SQL SERVER.

After you rewrite your table, which is small so a breeze. Open in visual studio "Server Explorer" And under Data Connections - Add New connection - point to the Employee table add - test connection, then right click the connection hit "Properties" in visual studio you will see connection string just copy and paste it. The rest of your code looks fine, and these type of errors are almost always string related. I hope that helps if you already got it fixed maybe some in the future will run into the same issue (Common).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900