views:

77

answers:

2

Using LINQ to Entities, I have the following code:

public Foo GetFooByID(int id)
{
 return _db.Foo.First(m => m.ID == id);
}

public Bar GetBarByID(int id)
{
 return _db.Bar.First(m => m.ID == id);
}

Is there a way to refactor this using generics?

+2  A: 

You could do something like the LINQ to SQL DataContext.GetTable method:

public T GetById<T>(int id)
{
  return _db.GetTable<T>().First(m => m.ID = id);
}

Then you would call it like so:

GetById<Foo>(10);
GetById<Bar>(10);
scottm
That looks exactly like what I was hoping for, except that LINQ to Entities doesn't use DataContext.
chris
you could use Type.GetProperties on your _db to see if it has any properties of type T.
scottm
For some reason, Type.GetType("myEDMX") returns null.
chris
@chris if you use the fully qualified name you get a type instead of null. (If you're unsure about the fully qualified name write this in watch/immediate window: typeof(yourtype).AssemblyQualifiedName (you might be able to use FullName too)
Rune FS
A: 

You'll need to abstract access to the property Foo and Bar on _db first. Then the generic part becomes pretty straight forward.

public T GetByID<T>(int id) 
{
 return _db.GetCollection<T>().First<T>(m => m.ID == id);
}

You might need to constrain T to a type that has the ID property if the compiler complains.

public T GetByID<T>(int id) where T : IHaveID
{
}
dkackman