【问题标题】:SqlException: Invalid column name 'EmployeeID1'SqlException:列名“EmployeeID1”无效
【发布时间】:2020-03-28 20:49:01
【问题描述】:

我目前正在尝试使用 Visual Studio 2019 制作一个 ASP.NET Core Web 应用程序。该应用程序的目的是显示从我导入的 localdb 数据库访问的所有数据。应用程序应该将所有信息正确地输出到表格中,并且用户应该能够创建新记录、编辑、删除以及在不同的屏幕上查看单个记录的详细信息。

当我尝试启动应用程序时,我不断收到以下错误:

SqlException:列名“EmployeeID1”无效。

以下屏幕截图是我尝试从中提取数据的数据库结构:

Database Structure

这个截图是文件结构:

File Structure

这就是我试图在表格中显示信息的方式:

Code

启动应用程序时显示的错误如下:

SqlException:列名“EmployeeID1”无效。

System.Data.SqlClient.SqlCommand+ c.b__122_0(任务结果)
System.Threading.Tasks.ContinuationResultTaskFromResultTask.InnerInvoke()
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback 回调, 对象状态)
System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot)
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection 连接,DbCommandMethod 执行方法,IReadOnlyDictionary 参数值,CancellationToken 取消令牌)
Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator.BufferlessMoveNext(DbContext , bool buffer, CancellationToken cancelToken)
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync(TState state, Func> operation, Func>> verifySucceeded, CancellationToken cancelToken)
Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator.MoveNext(CancellationToken cancelToken) System.Linq.AsyncEnumerable+SelectEnumerableAsyncIterator.MoveNextCore(CancellationToken cancelToken) System.Linq.AsyncEnumerable+AsyncIterator.MoveNext(CancellationToken cancelToken) Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor+EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancelToken) System.Linq.AsyncEnumerable.Aggregate
(IAsyncEnumerable 源,TAccumulate 种子,Func 累加器,Func resultSelector,CancellationToken cancelToken) Index.cshtml.cs 中的 WebApp2.IndexModel.OnGetAsync() -

        //public IList<Employee> Employee { get; set; }
        public IList<Employee> Employees { get;set; }

        public async Task OnGetAsync()
        {
            Employees = await _context.Employees.ToListAsync();
        }
    }
}
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+NonGenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.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.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

它一直对我说的主要信息是错误存在于以下代码中:

 Employees = await _context.Employees.ToListAsync();

以下代码是我在 Models 文件夹中的 Employee.cs 文件的代码:

using System;
using System.Collections.Generic;

namespace WebApp2.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string HomePhone { get; set; }
        public string Extension { get; set; }
        public string Notes { get; set; }
        public int ReportsTo { get; set; }
        public string PhotoPath { get; set; }

        public ICollection<Employee> Employees { get; set; }
    }
}

下一个代码是我目前用于我的 index.cshtml.cs 文件的代码。错误来自此代码的最后一行代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using WebApp2.Models;

namespace WebApp2
{
    public class IndexModel : PageModel
    {
        private readonly WebApp2.Models.Northwind _context;

        public IndexModel(WebApp2.Models.Northwind context)
        {
            _context = context;
        }

        //public IList<Employee> Employee { get; set; }
        public IList<Employee> Employees { get;set; }

        public async Task OnGetAsync()
        {
            Employees = await _context.Employees.ToListAsync();
        }
    }
}

我对此只是新手,对为什么会发生这种情况没有太多了解,因此感谢您的帮助。关于这个问题,stackoverflow 上有一些答案,但从答案中我不完全确定如何根据我的情况调整它。我希望我已经提供了足够的细节来说明为什么会发生这种情况。如果没有,请询​​问更多信息,我可以让你知道。谢谢。

【问题讨论】:

  • 还想指出,我根本不需要显示“照片”字段,这就是我将其从employee.cs 文件中删除的原因。
  • 为什么在Employee类中有一个Employees集合?您试图表示的与该属性的关系是什么?如果您注释掉该属性会发生什么?
  • 这真的很令人困惑,但我正在尝试实现我在此处遵循的本教程:docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/… 与我的其他应用程序正确连接到导入的数据库。 Index.cshtml.cs 之类的东西正在连接到该员工类。以及Edit.cshtml.cs、Details.cshtml.cs、Delete.cshtml.cs和Create.cshtml.cs

标签: c# database asp.net-core database-connection visual-studio-2019


【解决方案1】:

公共ICollection员工{得到;放; }

您需要将ReportsTo 配置为管理器导航属性的外键属性。例如

 public int ReportsTo { get; set; }

 [ForeignKey(nameof(Employee.ReportsTo))]
 public virtual Employee Manager {get;set;}

 public ICollection<Employee> Employees { get; set; }

【讨论】:

  • 这是我目前在Employees表的表定义中拥有的:CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED ([EmployeeID] ASC),CONSTRAINT [FK_Employees_Employees] FOREIGN KEY ([ReportsTo]) REFERENCES [ dbo].[Employees] ([EmployeeID]), CONSTRAINT [CK_Birthdate] CHECK ([BirthDate]
  • 对,但你没有告诉 EF ReportsTo 是外键属性。
  • 当我将您提供的代码插入到employees.cs 文件中时,它说找不到类型或命名空间名称“ForeignKey”,那我还要更改什么?抱歉,这种工作不太好。
  • 尝试添加:using System.ComponentModel.DataAnnotations.Schema; 或查看 Visual Studio 中的快速重构。
  • 谢谢伙计。它解决了我遇到的主要错误,但现在出现了一个不同的错误,我想我可能知道如何修复。欣赏它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 2018-06-29
  • 1970-01-01
  • 2020-09-23
  • 2021-04-29
  • 1970-01-01
相关资源
最近更新 更多