【发布时间】:2020-03-29 06:33:34
【问题描述】:
这是我从我的程序创建和链接数据库的步骤:
- 创建表
- 创建模型:Class 和 DBContext
- 点击按钮创建Controller,会自动生成controller和Viewer
- 检查appsettings.json中的连接字符串
- 在 Startup.cs 中添加上下文 ConnectionString
它总是得到
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 更新 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
modelBuildervsCREATE TABLE(fx:Start:stringvsvarchar(10)vsSMALLDATETIME)? -
与您的问题无关,但
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