简体   繁体   English

使用“FromSqlRaw”命令调用存储过程返回错误

[英]Calling stored procedure with “FromSqlRaw” command returning an error

I have seen this error in similar questions but with this being my first stab at.Net Core I want to make sure that my c# code is not the culprit.我在类似的问题中看到了这个错误,但这是我第一次尝试.Net Core,我想确保我的 c# 代码不是罪魁祸首。 The error is coming when the stored procedure is being called via FromSqlRaw command.通过FromSqlRaw命令调用存储过程时出现错误。 I verified I am sending the correct values to the FromSqlRaw command but error is complaining about a key?我确认我正在向FromSqlRaw命令发送正确的值,但错误是在抱怨一个键?

Please see code below:请看下面的代码:

Controller Controller

public class HomeController : Controller
{
    private IStudent _info;

    private readonly StudentInformation _studentInformation;

    public HomeController(IStudent info)
    {
        _info = info;
    }

    //public async Task<IActionResult> Index([FromQuery] Student student)
    public IActionResult Index([FromQuery] Student student)
    {
        int id = student.Id;

        if (id == 0) 
        {
            return NotFound(); 
        }

        var model = _info.GetById(id);

        return View(model);
    }
}

Student Class学生 Class

public class Student
{
    public int Id_Num { get; set; }

    public string StudentName { get; set; }
    public string PreferredName { get; set; }
    public string Gender { get; set; }

    public string DOB { get; set; }
    public string Resident { get; set; }

    public string F1Visa { get; set; }
    public string Division { get; set; }
    public string Tuition { get; set; }
    public string cohort { get; set; }
    public string Ferpa { get; set; }
} 

public class StudentInformationService : IStudent
{
    private StudentInfo _info;

    public StudentInformationService(StudentInfo info)
    {
        _info = info;
    }

    public IEnumerable<Student> GetAll()
    {
        throw new NotImplementedException();
    }

    public Student GetById(int id)
    {
        return _info.StudentRow
                   .FromSqlRaw("StudentRegistrationInfo @IdNum, @OldIdNum", 
                               new SqlParameter("IdNum", id),
                               new SqlParameter("OldIdNum", id))
                   .AsEnumerable().FirstOrDefault();
    }
}

Here is the error:这是错误:

InvalidOperationException: The entity type 'Student' requires a primary key to be defined. InvalidOperationException:实体类型“学生”需要定义主键。 If you intended to use a keyless entity type call 'HasNoKey()'.如果您打算使用无密钥实体类型,请调用“HasNoKey()”。

Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model, IDiagnosticsLogger logger) Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model,IDiagnosticsLogger 记录器)

Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger logger) Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model,IDiagnosticsLogger 记录器)

Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger logger) Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model,IDiagnosticsLogger 记录器)

Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger logger) Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerModelValidator.Validate(IModel model,IDiagnosticsLogger 记录器)

Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ImmediateConventionScope.OnModelFinalized(IConventionModelBuilder modelBuilder) Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ImmediateConventionScope.OnModelFinalized(IConventionModelBuilder modelBuilder)

Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel() Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()

Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder) Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext 上下文,IConventionSetBuilder 约定SetBuilder)

Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()

Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model() Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite,RuntimeResolverContext 上下文)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSiteMain(ServiceCallSite callSite,TArgument 参数)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite,RuntimeResolverContext 上下文,ServiceProviderEngineScope serviceProviderEngine,RuntimeResolverLock lockType)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite,RuntimeResolverContext 上下文)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(ServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(ServiceCallSite callSite,TArgument 参数)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite,RuntimeResolverContext 上下文)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSiteMain(ServiceCallSite callSite,TArgument 参数)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite,RuntimeResolverContext 上下文,ServiceProviderEngineScope serviceProviderEngine,RuntimeResolverLock lockType)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite,RuntimeResolverContext 上下文)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(ServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(ServiceCallSite callSite,TArgument 参数)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite,ServiceProviderEngineScope 范围)

Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供程序,类型 serviceType)

Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供程序)

Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()

Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()

Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()

Microsoft.EntityFrameworkCore.DbContext.get_Model() Microsoft.EntityFrameworkCore.DbContext.get_Model()

Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityType() Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityType()

Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityQueryable() Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityQueryable()

Microsoft.EntityFrameworkCore.Internal.InternalDbSet.System.Linq.IQueryable.get_Provider() Microsoft.EntityFrameworkCore.Internal.InternalDbSet.System.Linq.IQueryable.get_Provider()

Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSqlRaw(DbSet source, string sql, Object[] parameters) Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSqlRaw(DbSet 源,字符串 sql,Object[] 参数)

StudentServices.StudentInformationService.GetById(int id) in StudentInformationService.cs + StudentServices.StudentInformationService.GetById(int id) 在 StudentInformationService.cs +

  1. return _info.StudentRow.FromSqlRaw("StudentRegistrationInfo @IdNum, @OldIdNum", return _info.StudentRow.FromSqlRaw("StudentRegistrationInfo @IdNum, @OldIdNum",

StudentChecklist.Controllers.HomeController.Index(Student student) in HomeController.cs + HomeController.cs 中的 StudentChecklist.Controllers.HomeController.Index(Student student) +

  1. var model = _info.GetById(id); var model = _info.GetById(id);

lambda_method(Closure, object, Object[] ) lambda_method(闭包,object,对象[])

Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, Object[] parameters) Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(对象目标,Object[] 参数)

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__12.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__12.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__10.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__10.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext 上下文)

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__14.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__14.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__22.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__22.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext 上下文)

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__17.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__17.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__15.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__15.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)

Microsoft.AspNetCore.Builder.RouterMiddleware+d__4.MoveNext() Microsoft.AspNetCore.Builder.RouterMiddleware+d__4.MoveNext()

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

The error is really quite clear - your Student model class doesn't define a primary key for the entity (which it should - always).错误非常清楚 - 您的Student model class没有定义实体的主键(它应该 - 总是)。

By convention , Id or (classname)Id (here: StudentId ) would automatically be considered the primary key - since you have neither of these, you need to explicitly annotate the column to be used as primary key - most likely the Id_Num column - with a [Key] annotation - like this:按照惯例Id(classname)Id (这里: StudentId )将自动被视为主键 - 因为您没有这些,您需要显式注释要用作主键的列 - 很可能是Id_Num列 - 与一个[Key]注释 - 像这样:

public class Student
{
    [Key]
    public int Id_Num { get; set; }

    // remainder of your properties
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM