How to receive unique data in asp net mvc

1

I have the following model called Conta :

public int Codigo { get; set; }
public string Nome { get; set; }
public int Prazo { get; set; }

Assuming I want to do a select (without using lambda) and just bring the Name property, in this case I've created a struct:

struct getNomeConta
{
    public string Nome { get; set; }
}

and I made the select:

getNomeConta = db.Database.SqlQuery<getNomeConta>(strSql).FirstOrDefault();

where strSQl is my SQL string that returns the value of the name only.

This code has been rushed to meet the requester, but I want to change it, preferably using lambda to do the select, but only the name (without loading the model Conta integer)

    
asked by anonymous 04.07.2014 / 15:42

1 answer

1

Lambda Expression

Obs: Db is your DbContext

IList<String> Nomes = db.Conta.Select(x => x.Nome).ToList(); // para lista de nomes
String Nome = db.Conta.Where(x = x.Codigo == 1).Select(x => x.Nome).FirstOrDefault(); // 1 nome

Another tip:

You could use the code you just made, but you do not even need to create a Struct . As it is only the Name and it should be a VarChar ( String ) could be like this:

String Nome = db.Database.SqlQuery<String>("SELECT Nome FROM Conta Where Codigo = 1").FirstOrDefault();

Note: You will only create a Struct or Classe when that SQL brings more data.     

04.07.2014 / 16:03