Perform database mapping for DbSetT.SqlQuery ()

1

Error while executing SqlQuery from my DbSet.

  

There is no mapping of the System.Data.Entity.Core.Objects.ObjectParameter object type to a native type managed provider.

I would like to leave my generic database, so I put the parameters as ObjectParameter, how do I do this mapping from ObjectParameter to SqlParameter?

    public static ICollection<T> GetMany(string where, params object[] parameters)
    {
        object[] objParameters = new object[parameters.Count()];

        Type type = typeof(T);
        DbSet<T> dbSet = _context.Set<T>();

        string sql = " SELECT * FROM " + type.Name.ToUpper() + " WHERE " + where;

        int startPosition = 0;
        int stopPosition = 0;
        int contador = 0;

        //Colocar espaço apenas para controle.
        sql = sql.Insert(sql.Length, " ");

        // Montar Parametros.
        for (int i = 0; i < sql.Length; i++)
        {
            if (sql[i] == '@')
            {
                startPosition = i + 1;
                for (int a = i; a < sql.Length; a++)
                {
                    if (sql[a] == ' ')
                    {
                        stopPosition = a + 1;
                        string nomeParameter = sql.Substring(startPosition, stopPosition - startPosition);
                        ObjectParameter parameter = new ObjectParameter(nomeParameter.Trim(), parameters[contador]);
                        objParameters[contador] = parameter;
                        contador++;
                        break;                            
                    }
                }
            }
        }

        var registros = dbSet.SqlQuery(sql, objParameters).ToArray<T>();

        if (registros != null)
            return registros;
        return null;
    }
    
asked by anonymous 23.06.2017 / 22:07

1 answer

2

Being a mapped entity in EF, you could do this:

public IEnumerable<T> GetMany(Expression<Func<T, bool>> where = null)
{
    IQueryable<T> query = Db.Set<T>();

    if (where != null)
    {
        query = query.Where(where);
    }

    return query.AsNoTracking().ToList();
}

Calling this method would look something like this:

var lista = GetMany(p => p.AlgumaPropriedade == algumValor);

EDIT: IQueryable is an interface inherited from IEnumerable, as well as IList, for example, as seen on this link .

While the Expression<Func<T, bool>> is the same as the Linq Where parameter used.

You should use an instance of the class where you put the GetMany method.

    
24.06.2017 / 01:05