【问题标题】:SqlException: Invalid object name in .core 2.1SqlException:.core 2.1 中的对象名称无效
【发布时间】:2020-03-29 06:33:34
【问题描述】:

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

  1. 创建表
  2. 创建模型:Class 和 DBContext
  3. 点击按钮创建Controller,会自动生成controller和Viewer
  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. 在文件夹中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. 自动创建,不特殊
  2. 使用DefaultConnection,这是程序的初始化值
  3. ConfigureServices函数中,添加:
services.AddDbContext<ProjectLogContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

我还在 NuGet 控制台中通过命令 Update-Database -Context ProjectLogContext 更新 DB。

我还能做什么?

[更新]

当我想查看索引时出现 ALL ERROR MSG(在 DB ProjectLog 中按 ID 列出所有信息):

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)

【问题讨论】:

  • 1.提供堆栈跟踪的完整异常 2. 为什么某些字段在模型中具有不同的类型 vs modelBuilder vs CREATE TABLE (fx: Start : string vs varchar(10) vs SMALLDATETIME)?
  • 与您的问题无关,但 TEXT 已被弃用,并且它与新的 TIME 类型并没有放在一个表中。 (即使其他表将其用于​​现有数据也是如此,因为它很容易转换。)使用VARCHAR(MAX)NVARCHAR(MAX),或者更好的是,为您的字符串使用合理的大小(例如VARCHAR(255) 用于Hostname) .尽管有这个名字,TEXT 不是通用字符串类型,不应该像它一样使用。
  • 你的上下文是ProjectLogs(复数),但你的表是[ProjectLog]。对 EF 没有太多经验我不知道它是否足够聪明以默认处理复数,或者您是否需要以另一种方式处理不匹配。
  • 感谢您的所有建议!第一次用C#连接SQL,不知道SQL里面的类型。

标签: c# visual-studio-2017 asp.net-core-2.1


【解决方案1】:

@Crowcoder 在上面的 cmets 中是正确的,但错误地将约定与上下文名称相关联。它实际上基于您的实体名称,即ProjectLog。按照惯例,EF 会将其与名为 ProjectLogs(复数形式)的表关联,而您的表名为 ProjectLog(单数形式)。长与短:您需要将您的表格重命名为ProjectLogs

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

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

有关在 EF Core 中使用现有数据库的更多信息,请参阅docs

【讨论】:

  • 感谢您的分享!在我更改表名后,它就可以工作了!我参考了一些类似文档的文章。也许我可以尝试其他关键字(大声笑)。我什至不确定我使用哪种数据库类型......(我看到很多人与 EF 讨论)现在我知道它命名为 EF! (我认为是之前的SQL server)
  • EF/EF Core 是 ORM(对象关系映射器)。它们从数据库中获取数据并转换为 CLR 对象,反之亦然。 SQL Server 是一个数据库,如 Postgresql、MySQL 等。EF 与 SQL Server 一起工作。这不是一回事。
猜你喜欢
  • 1970-01-01
  • 2017-06-14
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多