I created a Project to learn about web api and entity framework. Well, when I try to connect my service with the database, the service did not retrieve the data from database. Below is my connection string:
<add name="CotacaoContext" connectionString="Data Source=Minha_Maquina\Instancia; Initial Catalog=Cotacao; User Id=sa; Password=d123" providerName="System.Data.SqlClient" />
This is my controller and the method GetUsuarios. This method(GetUsuarios) retrieves all data from DB(Table=Usuarios).
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);
}
}
Context class with respective DBSet:
public class CotacaoContext : DbContext
{
public CotacaoContext()
: base("name=CotacaoContext")
{
}
public DbSet<Usuarios> Usuario { get; set; }
public DbSet<Login> Login { get; set; }
}
model class
public class Usuarios
{
public int Id { get; set; }
public int Tipo_Usuario { get; set; }
public string NMUsuario { get; set; }
public string Senha { get; set; }
}
When I debug this line
return contexto.Usuario.AsEnumerable();
I have this problem:
my table has 6 records and in the image 6 records appear in this format " ? ". What does it mean?
Solved.I needed only a ToList() like this:
return contexto.Usuario.AsEnumerable().ToList();
I saw this answer here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.