Pregunta

I'am currently migrating our old system to .Net and I encountered this problem. I want to return the result but I still need to refine it after the function, but using this code, I don't have a choice but to call the result from the database and filter an in-memory result instead which is poor performance.

public IQueryable<User> GetUser(string[] accessCodes)
{
    string condition = "";
    if (accessCodes == null)
    {
         condition = " AccessCode IS NOT NULL "
    }
    else
    {
        for (int i = 0; i <= accessCodes.Length - 1; i++)
        {
            condition += " AccessCode LIKE '%" + accessCodes[i].ToString() + "%' ";
            if (i + 1 <= code.Length - 1)
            {
                condition += " OR ";
            }
        }
    }

    return context.ExecuteQuery<User>("SELECT * FROM User WHERE " + condition, null).ToList();
}

I've tried this approach this but i'm stuck:

public IQueryable<User> GetUser(string[] accessCodes)
{
    IQueryable<User> basequery = from u in context.User 
                                 select u;

    if (accessCodes == null)
    {
         basequery = basequery.Where(n => n.AccessCode != null);
    }
    else
    {
        for (int i = 0; i <= accessCodes.Length - 1; i++)
        {
            // what am I supposed to do here?
        }
    }

    return basequery;
}

I'm hoping that there are solutions which do not require third party libraries.

¿Fue útil?

Solución

You can try with Any:

else
{
    output = output.Where(u => accessCodes.Any(a => u.AccessCode.Contains(a)));
}

or you can use PredicateBuilder:

if (accessCodes == null)
{
    output = output.Where(u => u.AccessCode == null);
}
else
{
    var predicate = PredicateBuilder.False<User>();

    for (int i = 0; i <= accessCodes.Length - 1; i++)
    {
        predicate = predicate.Or(u => u.AccessCode.Contains(accessCodes[i]))
    }

    output = output.Where(predicate);
}

I also changed your if part: Where method does not modify source, it returns new query definition, so you have to assign it back to output to make it work.

Otros consejos

This should work for you:

IQueryable<User> basequery = from u in context.User 
                             select u;
if (accessCodes == null)
{
    basequery = basequery.Where(u => u.AccessCode != null);
}
else
{
    basequery = basequery.Where(u => accessCodes.Contains(u=>u.AccessCode));
}

also make sure you return basequery, since output in your method is not defined and not used.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top