简体   繁体   中英

SqlException: Invalid object name in .core 2.1

here is my step to create and link the DB from my program:

  1. create a table
  2. create the model: Class and DBContext
  3. create the Controller by click the button and it would automatically generate both of controller and Viewer
  4. check the connection string in appsettings.json
  5. add Context ConnectionString in Startup.cs and it always got SqlException: Invalid object name error i am sure my connectionstring is correct because another table connection succeeds in the same DB.

here is my code:

  1. dbo.ProjectLog.sql
CREATE TABLE [dbo].[ProjectLog] (
    [ID]              INT           NOT NULL,
    [Date]            DATE          NOT NULL,
    [ExeUser]         TEXT          NOT NULL,
    [RD]              TEXT          NOT NULL,
    [Time]            TIME (7)      NULL,
    [Start]           SMALLDATETIME NULL,
    [End]             SMALLDATETIME NULL,
    [Host]            TEXT          NULL,
    [Environment]     TEXT          NULL,
    [ProjectFullName] VARCHAR (50)  NULL,
    [ProjectName]     VARCHAR (50)  NOT NULL,
    [ProjectVersion]  VARCHAR (50)  NULL,
    [Critical]        INT           NULL,
    [High]            INT           NULL,
    [Low]             INT           NULL,
    [MainProjectID]   INT           NULL,
    [Comment]         TEXT          NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC)
);
  1. in folder Models : ProjectLog.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace WebTryLogin.Models
{
    public class Project
    {
        [Key]
        public int ID { get; set; }
        public string Date { get; set; }
        public string ExeUser { get; set; }
        public string RD { get; set; }
        public int Time { get; set; }
        public string Start { get; set; }
        public string End { get; set; }
        public string Host { get; set; }
        public string Environment { get; set; }
        public string ProjectFullName { get; set; }
        public string ProjectName { get; set; }
        public string ProjectVersion { get; set; }
        public int Critical { get; set; }
        public int High { get; set; }
        public int Low { get; set; }
        public int MainProjectID { get; set; }
        public string Comment { get; set; }
    }
    public class ProjectLogContext : DbContext
    {
        public ProjectLogContext(DbContextOptions<ProjectLogContext> options) : base(options)
        {

        }

        public DbSet<Project> ProjectLogs { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Project>(entity =>
            {
                entity.Property(e => e.ID).HasColumnType("int(8)");
                entity.Property(e => e.Date).HasColumnType("varchar(10)");
                entity.Property(e => e.ExeUser).HasColumnType("varchar(20)");
                entity.Property(e => e.RD).HasColumnType("varchar(20)");
                entity.Property(e => e.Time).HasColumnType("varchar(10)");
                entity.Property(e => e.Time).HasColumnType("varchar(10)");
                entity.Property(e => e.Start).HasColumnType("varchar(10)");
                entity.Property(e => e.End).HasColumnType("varchar(10)");
                entity.Property(e => e.Host).HasColumnType("varchar(15)");
                entity.Property(e => e.Environment).HasColumnType("varchar(50)");
                entity.Property(e => e.ProjectFullName).HasColumnType("varchar(50)");
                entity.Property(e => e.ProjectName).HasColumnType("varchar(50)");
                entity.Property(e => e.ProjectVersion).HasColumnType("varchar(50)");
                entity.Property(e => e.Critical).HasColumnType("int(10)");
                entity.Property(e => e.High).HasColumnType("int(10)");
                entity.Property(e => e.Low).HasColumnType("int(10)");
                entity.Property(e => e.MainProjectID).HasColumnType("int(8)");
                entity.Property(e => e.Comment).HasColumnType("varchar(10)");
            });
        }
    }

}
  1. create automatic, not special
  2. use the DefaultConnection that is a initialize value by program
  3. in ConfigureServices function, add:
services.AddDbContext<ProjectLogContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

and i also update DB by command Update-Database -Context ProjectLogContext in NuGet Console.

what could i do else?

[UPDATE]

ALL ERROR MSG when i want to view index (list all info by ID in DB ProjectLog ):

An unhandled exception occurred while processing the request.

SqlException: Invalid object name 'ProjectLogs'.
System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__122_0(Task<SqlDataReader> result)
DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)

SqlException: Invalid object name 'ProjectLogs'.

System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__122_0(Task<SqlDataReader> result)
System.Threading.Tasks.ContinuationResultTaskFromResultTask<TAntecedentResult, TResult>.InnerInvoke()
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot)
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary<string, object> parameterValues, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)

DbUpdateException: An error occurred while updating the entries. See the inner exception for details.

Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple<IEnumerable<ModificationCommandBatch>, IRelationalConnection> parameters, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList<InternalEntityEntry> entriesToSave, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
WebTryLogin.Controllers.ProjectsController.Create(Project project) in ProjectsController.cs
+     63.           await _context.SaveChangesAsync();
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

@Crowcoder is correct in the comments above, but incorrectly associated the convention with the context name. It's actually based on the name of your entity, ie ProjectLog . By convention, EF will associate that with a table named ProjectLogs , plural, and your table is named ProjectLog , singular. Long and short: you need to rename your table to ProjectLogs .

Also, FWIW, you should not manually create your entity classes or context if you're going to use an existing database, or simply want to go a "database-first" route. Instead, you should scaffold your context and entities into your project, and continue to do so to update them if and when you make changes to the database.

dotnet ef dbcontext scaffold "[connection string]" Microsoft.EntityFrameworkCore.SqlServer -o Models

For additional information about using an existing database with EF Core, see the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM