Generics extention for getting 3.5 EF object with Data Services

May 9, 2011

In my latest project implemented with EF 3.5 and ADO.NET Data Services, there was the constant need of getting entity objects from DB by ID(…). This generics routine retrieves an object (of the generated DataServiceContext types) by its respective Id of int, double, decimal, or Guid:

public static T GetById<T,U>(this DataServiceContext ctx,   U id)
  where T: INotifyPropertyChanged
  where U: struct
{
  var atts = typeof(T).GetCustomAttributes(false);

  var entitySet = (atts.First(a=>a is EntitySetAttribute)
    as EntitySetAttribute).EntitySet;

  var key = (atts.First(a=> a is DataServiceKeyAttribute)
    as DataServiceKeyAttribute).KeyNames.First();

  var query = string.Format(new[]
  {
    new {Query = "{0} eq guid'{1}'", Expr = id is Guid},
    new {Query = "{0} eq {1}",
     Expr = id is double || id is decimal || id is int}
  }
   .First(q=> q.Expr).Query, key, id);

  return ctx.CreateQuery(entitySet)
    .AddQueryOption("$filter", query).First();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: