使用SQL Server而不使用实体框架的ASP.NET Web还原API? [英] An ASP.NET web restore API with SQL server without using entity framework?

查看:66
本文介绍了使用SQL Server而不使用实体框架的ASP.NET Web还原API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

How to create an ASP.NET Web Restore API with SQL Server without using entity framework?







I'm having trouble finding a tutorial to create an API Rest ASP.NET Web with SQL Server without entity framework, can someone help me? =( 





我尝试过:



连接:





What I have tried:

conection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Teste.Controllers;

namespace Teste.Models
{
    public class Conexaocs : IDisposable
    {
        private SqlConnection connection;

        public void ConectaBD()
        {
            string stringConexao = "Data Source=localhost;Initial Catalog=Teste;Integrated Security=true";
            connection = new SqlConnection(stringConexao);
            connection.Open();
        }
        public void Dispose()
        {
            //connection.Close();
        }
        public void InserirMarca(Marca marca)
        {
        }
        public List<Marca> consultaMarcas()
        {
            List<Marca> marcas = new List<Marca>();

            SqlCommand query = new SqlCommand();
            query.Connection = connection;
            query.CommandText = "@SELECT * FROM Marca";

            SqlDataReader leitura = query.ExecuteReader();

            while (leitura.Read())
            {
                Marca marca = new Marca();
                marca.MarcaId = (int)leitura["MarcaId"];
                marca.Nome = (string)leitura["Nome"];

                marcas.Add(marca);
            }
            return marcas;
        }
    }
}







和控制器








and controller


sing System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Teste.Models;



namespace Teste.Controllers
{
    public class MarcaController : ApiController
    {
        Conexaocs conexao = new Conexaocs();
        private static List<Marca> marcas = new List<Marca>();

        public List<Marca> Get()
        {
            try
            {
                using (conexao = new Conexaocs())
                {
                    marcas = conexao.consultaMarcas();
                    return marcas;
                }
            }
            catch (SqlException e)
            {
                
                return marcas;
            }
        }
}





和错误:

< br $>



and error:

{
    "Message": "Ocorreu um erro.",
    "ExceptionMessage": "ExecuteReader: propriedade Connection não foi inicializada.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": "   em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)\r\n   em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)\r\n   em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   em System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   em System.Data.SqlClient.SqlCommand.ExecuteReader()\r\n   em Teste.Models.Conexaocs.consultaMarcas() na D:\\C#\\Teste\\Teste\\Models\\Conexaocs.cs:linha 35\r\n   em Teste.Controllers.MarcaController.Get() na D:\\C#\\Teste\\Teste\\Controllers\\MarcaController.cs:linha 25\r\n   em lambda_method(Closure , Object , Object[] )\r\n   em System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.<GetExecutor>b__3(Object instance, Object[] methodParameters)\r\n   em System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   em System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\r\n   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   em System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\r\n   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   em System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\r\n   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   em System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"
}

推荐答案

虽然您的班级确定了连接,但 consultaMarcas 方法永远不会打开它。



尝试在方法上添加对
While your class does have connection defined, the consultaMarcas method never opens it.

Try adding a call to
ConectaBD()

的调用


这篇关于使用SQL Server而不使用实体框架的ASP.NET Web还原API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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