1
I did a test project, called quotation to use the Web API and Entity. Well, I went to my web.config and created my connection string like this:
<add name="CotacaoContext" connectionString="Data Source=Minha_Maquina\Instancia; Initial Catalog=Cotacao; User Id=sa; Password=d123" providerName="System.Data.SqlClient" />
This preacher is there, because before I had made an error of his absence, so I put it. In my controller I made a method to catch BD users and is giving up. This is my method in Controller (all code).
public class UsuarioController : ApiController
{
private CotacaoContext contexto = new CotacaoContext("CotacaoContext");
[AcceptVerbs("Get")]
public IEnumerable<Usuarios> GetUsuarios()
{
return contexto.Usuario.AsEnumerable();
}
public Usuarios GetUsuarioById(int id)
{
Usuarios usuario = contexto.Usuario.Find(id);
if(usuario == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return usuario;
}
protected override void Dispose(bool disposing)
{
contexto.Dispose();
base.Dispose(disposing);
}
}
This is my Context class that will create the Dbsets and connect to the database.
public class CotacaoContext : DbContext
{
public CotacaoContext(string connectionString)
: base(connectionString)
{
}
public DbSet<Usuarios> Usuario { get; set; }
public DbSet<Login> Login { get; set; }
}
And this is my model that abstracted the table from the database.
public class Usuarios
{
public int Id { get; set; }
public int Tipo_Usuario { get; set; }
public string NMUsuario { get; set; }
public string Senha { get; set; }
}
An important observation. There is 6 record in the table that I put in hand, and there is a table that makes a Foreign key in the user table, but as I’m testing the connection first, I haven’t put in my template yet. Below a print at debug time.
Note that when I put the mouse in the context variable, 6 items appear, but with a question mark (my table has 6 records). I am since last night on the internet, to try to find out why, but lack a little more knowledge(is what I am seeking). I wait.
Edit1 - An important point. The attribute [AcceptVerbs("Get")]
I put it later, in an attempt to hit.
Edit2 - Came a light. I need to do something in the web api routes archive?
Edit3 - When I run, both in the browser and in Postman, comes this result: []
Have you tried passing your connection string directly in the base(connectionString) of Dbcontext ? or base("Cotacaocontext")
– Marco Souza
I’ve done it before:
..("name=CotacaoContext")
. I also forgot to say, but I call my service that in the URL:http://localhost:6741/api/usuario
– pnet