Web API和sqlserver sqlconnection [英] Web API and a sqlserver sqlconnection

查看:563
本文介绍了Web API和sqlserver sqlconnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WebAPI的新手,但过去曾做过MVC。我创建了两个包含后端和EF等的WebServiceAlpha项目,以及使用Alpha的WebServiceBeta。

在WebServiceBeta中,我正在尝试创建一个数据访问层,因此我创建了一个名为DAL的类,它非常简单。我有SqlConnection,但是任何对其他任何代码进行编码的尝试都会导致名称j在当前上下文中不存在。

我所要做的就是连接到数据库。



我尝试过:



I'm new to WebAPI but have done MVC in the past. I created 2 projects WebServiceAlpha that houses the "backend" and EF etc, and WebServiceBeta that "uses" the Alpha.
In WebServiceBeta, I'm trying to create a data access layer so I created a class called DAL and it's very simple. I have the SqlConnection, but any attempt to code anything else results in "The name j does not exist in the current context".
All I'm trying to do is to connect to the database.

What I have tried:

namespace WebServiceBeta
{    
    public class DAL
    {
        SqlConnection j = new SqlConnection(@"data source=***;initial catalog=CRUDDB;User id=***;password=***;MultipleActiveResultSets=True");
        j.  // The name 'j.' does not exist in the current context
    }
}





控制器;但是,连接工作正常:



On the controller; however, the connection works fine:

public ActionResult Index( FormCollection frm )
 {
     SqlConnection j = new SqlConnection(@"data source=**;initial catalog=CRUDDB;User id=**;password=**;MultipleActiveResultSets=True")
     //Enumerable<mvcEmployeeModel> empList;
     j.Open();  // THIS WORKS FINE
     if ( j.State==ConnectionState.Open)
     {
         ViewBag.CnState = "Yea - I'm open!";
     }





我还缺少其他东西吗?我可以不要想象它是一个使用问题,我添加了System.Data.SqlClient和System.Data。



Is there something else I'm missing? I can't imagine it being a "using" issue, I've added System.Data.SqlClient and System.Data.

推荐答案

你试图在课堂上编写代码级别而不是类中的方法。这不会起作用。



在你的控制器中,你将代码放在索引方法中。在你的DAL课程中并非如此。
Your trying to write code at the class level instead of in methods in the class. That's not going to work.

In your controller, you're putting the code in the method Index. That's not true in your DAL class.


这篇关于Web API和sqlserver sqlconnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆