Using the Case When Then command with Entity Framework

2

I have the following structure corresponding to a table in my Database:

Cat_Codigo, 
Cat_Descricao, 
Cat_Observacao, 
Cat_Status

Where Cat_Status is defined by 0 or 1, where 0 -> Disabled and 1 - > Active.

But I do not want to display to the end user, 0 or 1, but Disable and Active, I know this is possible through the following SQL command

SELECT  cat_codigo As Codigo,  cat_descricao As Descricao, cat_observacao AS Observacao, 
CASE cat_status WHEN '1' THEN 'Ativo' WHEN '0' THEN 'Desativo' END AS Status FROM Categoria

Using the command CASE I can set this.

Now how do I do the same thing through the Entity Framework? Which method can I use to change the fields to a name. In my class the status attribute is as int , would this cause any problems too?

    
asked by anonymous 22.02.2017 / 15:40

3 answers

1

A simple way is to create an attribute with only get . It will not be stored in the data bank, and should answer you. In addition, it is reusable.

public class Categoria 
{
    public int Cat_Codigo  { get; set; }
    public string Cat_Descricao { get; set; }
    public string Cat_Observacao { get; set; }
    public int Cat_Status { get; set; }

    // c# 6
    public string DescricaoStatus => Cat_Status == 1 ? "Ativo" : "Inativo";
}

or

public string DescricaoStatus 
{
  get 
  {
    return Cat_Status == 1 ? "Ativo" : "Inativo";
  }
}
    
22.02.2017 / 15:51
1

One possibility would be to use the conditional operator ?: returns one of two values, depending on the value of a Boolean expression.

var categorias = context.Categoria.
        Select(a => new {
            Codigo = a.Cat_Codigo,
            Descricao = a.Cat_Descricao,
            Observacao = a.Cat_Observacao,
            Status = a.Cat_status == 0 ? "Ativo" : "Desativo"
        });
    
22.02.2017 / 15:58
0

I recommend that you create an object of type Returns with the same fields of the Bank only with a string attribute to be able to assign the value after listing, in this case a statusstr (string str).

Create a list of type Returns.

List<DaoRetorno> lista = conexao.Categoria.Select(x=> new DaoRetorno () { codigo = x.codigo, descricao = x.descricao, obs= x.obs, status=x.status }).toList();

foreach (item i in lista)
{
  if (i.status = 1){
       i.statusstr = 'Ativo';
  }
  else
  {
       i.statusstr = 'Desativo';
  }
}

In other words, it passes one by one and assigns the value to the list, after which your list will have the field filled, only use the value later.

    
22.02.2017 / 15:45