How to receive unique data in Asp net mvc

Asked

Viewed 130 times

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 select (without using lambda) and bring only the Name property, in which case I created a struct:

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

and made the select:

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

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

This code was made in a hurry to meet the requisitor, but I want to change it, preferably using lambda to select, but with only the name (without having to load the model Conta whole)

  • In fact when bringing the data from Conta you carry the Model all anyway. Bring all the columns or do not generate impact on the performance, whether this is the concern.

1 answer

1


Lambda Expression

Note: 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:

I could use the code you made, but you don’t even have to create a Struct. Since it is only the Name and the same must be one VarChar (String) could be so:

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

Obs: Just gonna create a Struct or Classe when that SQL bring more data.

  • 1

    Exactly. There is a link explaining the basics of this: http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx

  • 1

    Great reply! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.