SORU
17 Aralık 2008, ÇARŞAMBA


'İçerir()' Varlıklar bu Seri kullanarak geçici çözüm?

Where yan tümcesi kimliklerinin bir listesini kullanan bir sorgu, Silverlight ADO.NET Veri Hizmetleri istemci apı (ve bu nedenle Varlıkları bu Seri) oluşturmak için çalışıyorum. Herkes desteklenen İçeren bir çözüm biliyor mu?

Böyle bir şey yapmak istiyorum:

List<long?> txnIds = new List<long?>();
// Fill list 

var q = from t in svc.OpenTransaction
        where txnIds.Contains(t.OpenTransactionId)
        select t;

Bu çalıştı:

var q = from t in svc.OpenTransaction
where txnIds.Any<long>(tt => tt == t.OpenTransactionId)
select t;

Ama "yöntem 'Herhangi bir' desteklenmiyor".

CEVAP
1 Temmuz 2009, ÇARŞAMBA


Güncelleme:EF ≥ 4 doğrudan Contains destekler (Çıkış Any), herhangi bir çözüm gerekmez.

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));
}

//Optional - to allow static collection:
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
  (
    this ObjectQuery<TEntity> query,
    Expression<Func<TEntity, TValue>> selector,
    params TValue[] collection
  )
{
  return WhereIn(query, selector, (IEnumerable<TValue>)collection);
}

KULLANIMI:

public static void Main()
{
  using (MyObjectContext context = new MyObjectContext())
  {
    //Using method 1 - collection provided as collection
    var contacts1 =
      context.Contacts.WhereIn(c => c.Name, GetContactNames());

    //Using method 2 - collection provided statically
    var contacts2 = context.Contacts.WhereIn(c => c.Name,
      "Contact1",
      "Contact2",
      "Contact3",
      "Contact4"
      );
  }
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Android Authority

    Android Auth

    3 NİSAN 2011
  • boburnham

    boburnham

    11 Temmuz 2006
  • Google Developers

    Google Devel

    23 AĞUSTOS 2007