【发布时间】: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