What is the best solution? GetById with id not existing in DB

5

I'm making a call in my repository but the CPF does not always exist in the DB. When it does not exist in the database I get the following error.

Repository

public VendedorModel GetById(int CPF)
    {
        using (var db = new PowerVendasEntities())
        {
            var registro = db.Vendedor.Single(x => x.VendedorCPF == CPF);

            return VendedorFactory.ToModel(registro);
        }
    }

What is the best way to solve this problem?

    
asked by anonymous 12.01.2018 / 12:32

4 answers

3

You can use FirstOrDefault () or the

FirstOrDefault ():

  

Returns the first element of a sequence, or a default value if the   sequence does not contain elements.

SingleOrDefault ()

  

Returns the single element of a string or a default value if the   sequence is empty; this method raises an exception if there is more than one   element in sequence.

How would you look:

public VendedorModel GetById(int CPF)
    {
        using (var db = new PowerVendasEntities())
        {
            var registro = db.Vendedor.FirstOrDefault(x => x.VendedorCPF == CPF);

            return VendedorFactory.ToModel(registro);
        }
    }
    
12.01.2018 / 12:44
2

You can use the following:

public VendedorModel GetById(int CPF){
    using (var db = new PowerVendasEntities()){
         var registro = db.Vendedor.SingleOrDefault(x => x.VendedorCPF == CPF);
         return registro != null ? VendedorFactory.ToModel(registro) : null;
    }
}

Only by completing what has already been well explained in the accepted answer on SingleOrDefault() , in this case if the Bank does not find any Vendor with this CPF, it will return a null , using a #

12.01.2018 / 18:41
1

The problem with using Single is that it throws for the database a Top 2 , and if there are two records for the last filter it returns an error and if no record is found it also returns an error, that is, it expects only one record to be found in the database.

This is a problem because it causes performance loss, which has yet to be handled in the application errors.

The solution indicated is to use the methods; First or FirstOrDefault . You can even use SingleOrDefault , but you would still be sending a TOP 2 for the base and if there is more than one record it still returns an error.

    
15.01.2018 / 12:58
1

One solution option can also be this:

public VendedorModel GetById(int CPF)
{
    using (var db = new PowerVendasEntities())
    {
        var registro = db.Vendedor
            .Where(x => x.VendedorCPF == CPF)
            .FirstOrDefault();

        return VendedorFactory.ToModel(registro);
    }
}
    
29.04.2018 / 19:18