【问题标题】:System.Data.SqlClient.SqlException in Entity Framework (Web API)实体框架(Web API)中的 System.Data.SqlClient.SqlException
【发布时间】:2021-05-04 00:53:41
【问题描述】:

我的网络控制器代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Account;

namespace Account.Controllers
{
    public class ORDER_DETAILController : ApiController
    {
        private restaurantEntities db = new restaurantEntities();

        [HttpGet]
        [Route("api/ORDER_DETAIL/PendingOrders/{id}")]
        [ResponseType(typeof(ORDER_DETAIL))]
        public IQueryable<Orders> PendingOrders(int id)
        {
            Class1 obj = new Class1();
            return obj.GetOrders(id);
        }
    }
}

类:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Configuration;
 using System.Data;
 using System.Data.SqlClient;
 using Dapper;

 namespace AccountStoredProc.Controllers
 {
     public class Class1
     {
         public IQueryable<Orders> GetOrders(int id)
         {
             using(SqlConnection conn = new SqlConnection("integrated security = true ; data source = RAHUL - PAVILION;")) 
             {
                 conn.open();
                 return conn.Query<Orders>($"select * from ORDER_DETAIL WHERE VEN_ID={id} and ORD_STATUS='PENDING' ").AsQueryable();
             }    
          }
      }
 }

当我点击以下网址时:

https://localhost:44331/api/ORDER_DETAIL/PendingOrders/1

我收到此错误:

在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:命名管道提供者,错误:40 - 无法打开与 SQL Server 的连接)

System.Data.SqlClient.SqlException

我知道我在创建 EF 时已经打开了连接,但是如果没有名为 SqlConnection 变量的 conn 变量,我如何在 GetOrders() 中执行我的查询?如果没有 conn 变量,我将无法执行我的查询?

注意:连接建立在普通控制台应用程序和其他预定义方法(如 get、在帐户控制器中搜索)中有效,但在我的预定义方法中无效。

【问题讨论】:

  • 我怀疑你的机器名称是:“RAHUL - PAVILION”!?
  • @ErikEJ 同意。该连接字符串肯定会导致该错误。
  • 您遇到了 SQL 注入问题:您将 id 连接到查询中,您应该使用 SQL 参数,例如 @id

标签: c# asp.net entity-framework asp.net-web-api dapper


【解决方案1】:

请检查您的连接字符串,尤其是空格

连接字符串的示例格式:

 `connetionString = @"Data Source=WIN-50GP30FGO75; integrated security = true; Initial Catalog=Demodb;User ID=sa;Password=demol23";`

【讨论】:

  • 您不能混合集成安全性和用户名/密码
  • @ErikEJ 仅显示格式,即使您可以混合使用如果指定了用户 ID 和密码并且集成安全设置为 true,则用户 ID 和密码将被忽略并使用集成安全.
猜你喜欢
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2012-11-07
相关资源
最近更新 更多