Posts Tagged ‘entity-framework’

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