[英]SqlException: Invalid object name in .core 2.1
这是我从我的程序创建和链接数据库的步骤:
SqlException: Invalid object name
错误我确信我的连接SqlException: Invalid object name
是正确的,因为另一个表连接在同一个数据库中成功。这是我的代码:
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)
);
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)");
});
}
}
}
DefaultConnection
ConfigureServices
函数中,添加:services.AddDbContext<ProjectLogContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
我还通过 NuGet 控制台中的命令Update-Database -Context ProjectLogContext
。
我还能做什么?
[更新]
当我想查看索引时出现 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)
@Crowcoder 在上面的评论中是正确的,但错误地将约定与上下文名称相关联。 它实际上基于您的实体的名称,即ProjectLog
。 按照惯例,EF 会将其与名为ProjectLogs
复数表相关联,而您的表名为ProjectLog
单数。 长和短:您需要将表重命名为ProjectLogs
。
此外,FWIW,如果您要使用现有数据库,或者只想走“数据库优先”路线,则不应手动创建实体类或上下文。 相反,您应该将您的上下文和实体构建到您的项目中,并在您对数据库进行更改时继续这样做以更新它们。
dotnet ef dbcontext scaffold "[connection string]" Microsoft.EntityFrameworkCore.SqlServer -o Models
有关在 EF Core 中使用现有数据库的其他信息,请参阅文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.