SqlException:.core 2.1中无效的对象名称

问题描述 投票:-1回答:1

这是我从程序创建和链接数据库的步骤:

  1. 创建表
  2. 创建模型:类和DBContext
  3. 通过单击按钮创建控制器,它将自动生成控制器和查看器
  4. 检查appsettings.json中的连接字符串
  5. 在Startup.cs中添加上下文ConnectionString并且总是出现SqlException: Invalid object name错误我确定我的连接字符串正确,因为另一个表连接在同一数据库中成功。

这是我的代码:

  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. 在文件夹ModelsProjectLog.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. 自动创建,不特殊
  2. 使用通过程序初始化的值DefaultConnection
  3. ConfigureServices功能中,添加:
services.AddDbContext<ProjectLogContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

而且我还通过在NuGet Console中通过命令Update-Database -Context ProjectLogContext更新数据库。

我还能做什么?

[更新]

当我想查看索引时(通过数据库ProjectLog中的ID列出所有信息),所有错误MSG:

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)
c# visual-studio-2017 asp.net-core-2.1
1个回答
0
投票
@@ Crowcoder在上面的注释中是正确的,但是错误地将约定与上下文名称相关联。它实际上是基于您实体的名称,即ProjectLog。按照约定,EF会将其与名为ProjectLogs的表(复数)相关联,并且您的表名为ProjectLog的单数。长短:您需要将表重命名为ProjectLogs

此外,FWIW,如果要使用现有数据库,或者只是想走“数据库优先”路线,则不应手动创建实体类或上下文。相反,您应该将上下文和实体放入您的项目中,并在更改数据库时继续这样做以更新它们。

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

有关将现有数据库与EF Core一起使用的更多信息,请参见docs。>>
© www.soinside.com 2019 - 2024. All rights reserved.