How to make a max + 1 with lambda or linq but with tables from nothing, all null

1

I made this method and other attempts. With the table filled, okay, but with the table without data, it is giving error:

public int GeraIdBalanca()
{
    int chave = 0;
    var obj = contexto.Balancas.Max().IdBalanca;
    if (obj == 0)
        chave = 1;
    else
        chave = obj + 1;
    return chave;
}

I tried the table with information, I can bring the ID, but with the table zeroed, newly created gives me error.

    
asked by anonymous 17.08.2017 / 15:43

3 answers

3

The whole code can be written like this

public int GeraIdBalanca() => contexto.Balancas.Max()?.IdBalanca + 1 ?? 1;

Your problem is because you need to check if the return of Max is not null before you try to access the IdBalanca property.

var obj = contexto.Balancas.Max()?.IdBalanca ?? 1;

If you are using the Entity Framework, I already stress that your approach does not work and does not even make sense.

In EF, the method would need to be

public int GeraIdBalanca() => contexto.Balancas.Any() ? contexto.Balancas.Max(b => b.id) + 1 : 1;

Or, in a normal method

public int GeraIdBalanca()
{
    return contexto.Balancas.Any() ? contexto.Balancas.Max(b => b.id) + 1 : 1;
}
    
17.08.2017 / 15:46
2

I believe it can be done like this:

        var obj = contexto.Balancas.Max(b => b.IdBalanca);
        int chave = (obj == null ? 1 : obj + 1);
        return chave;
    
17.08.2017 / 15:46
0

You can use a Default solution for when your table did not have data.

public int GeraIdBalanca()
{
    return contexto.Balancas.Select(m => m.IdBalanca).DefaultIfEmpty(0).Max() + 1;
}
    
17.08.2017 / 16:10