As you use version 1 of the Entity Framework , also known as version 3.5, I see 2 possibilities to solve the problem.
1. One of them is to create an extension method for this.
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
IEnumerable<TValue> collection
)
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
if (!collection.Any())
return query.Where(t => false);
ParameterExpression p = selector.Parameters.Single();
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.Equal(selector.Body,
Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate((accumulate, equal) =>
Expression.Or(accumulate, equal));
return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}
To use it:
public List<Meta> ListaMetasDeCategorias(List<CategoriaMetaOrgao> ListaCategoriaMetaOrgao, int orgaoId, int temporadaId)
{
List<int> arrayIdCategorias = new List<int>();
foreach(CategoriaMetaOrgao categoriaMetaOrgao in ListaCategoriaMetaOrgao)
arrayIdCategorias.Add(categoriaMetaOrgao.CategoriaMeta.categoriaMetaId);
var q = from a in Repository.Context.Meta
where a.Temporada.temporadaId == temporadaId
&& a.Orgao.orgaoId == orgaoId
select a;
q.WhereIn(a => a.CategoriaMeta.categoriaMetaId, arrayIdCategorias);
return q.ToList();
}
2. The other solution and I do not recommend much is to transform your query to a list and then do the Contains
filter, the problem this way is that you are not doing the filter on select, so maybe making your query heavier.
public List<Meta> ListaMetasDeCategorias(List<CategoriaMetaOrgao> ListaCategoriaMetaOrgao, int orgaoId, int temporadaId)
{
List<int> arrayIdCategorias = new List<int>();
foreach(CategoriaMetaOrgao categoriaMetaOrgao in ListaCategoriaMetaOrgao)
arrayIdCategorias.Add(categoriaMetaOrgao.CategoriaMeta.categoriaMetaId);
var q = from a in Repository.Context.Meta
where a.Temporada.temporadaId == temporadaId
&& a.Orgao.orgaoId == orgaoId
select a;
var y = q.ToList().Where( a => arrayIdCategorias.Contains(a.CategoriaMeta.categoriaMetaId));
return y;
}
Note:
If you used Entity Framework 4 or higher, you could use Contains
, it takes a list and checks if an element is in that list.
public List<Meta> ListaMetasDeCategorias(List<CategoriaMetaOrgao> ListaCategoriaMetaOrgao, int orgaoId, int temporadaId)
{
List<int> arrayIdCategorias = new List<int>();
foreach(CategoriaMetaOrgao categoriaMetaOrgao in ListaCategoriaMetaOrgao)
arrayIdCategorias.Add(categoriaMetaOrgao.CategoriaMeta.categoriaMetaId);
var q = from a in Repository.Context.Meta
where a.Temporada.temporadaId == temporadaId
&& a.Orgao.orgaoId == orgaoId
&& arrayIdCategorias.Contains(a.CategoriaMeta.categoriaMetaId)
select a;
return q.ToList();
}