I am trying to come up with a generic way to pull an object by its Id in my repository. In my database, generally, all the IDs are primary keys and are of the type integer. There may be a case, down the road where that is not true, but I still want to maintain the same method for all objects. Here is what my Interface looks like now:
public interface IRepository<TE>
{
void Add(TE entity);
void AddOrAttach(TE entity);
void DeleteRelatedEntries(TE entity);
void DeleteRelatedEntries(TE entity, ObservableCollection<string> keyListOfIgnoreEntites);
void Delete(TE entity);
int Save();
//this is where I am stuck
TE GetById();
}
I have seen some code out there where reflection is used to get the ID of an object then parse all objects for that speicifc object (not ideal). I have also seen somethng like this:
TE GetById(Expression<Func<TE, bool>> predicate);
I got that idea from here.
I am not realy familiar with expressions yet and not sure if this will work for me or not. I guess it would, becuase I could include this expression:
var foo = GetById(f => f.Id == 1);
But I suppose that isn't really GetById, but rather I could use any expression to get what I want, right?
Any thoughts would be appreicated.
First, why is it a Repository<TE,TC>
instead of a Repository<T>
?
I use two methods:
TE GetById(int id){`
return _querySource.Single(x=>x.Id ==1);
}
IQueryable<TE> Query(Expression<Func<TE,bool>> predicate){
return _querySource.Where(predicate);
}
(I am assuming that you have an underlying IQueryable<TE>
field and I named it _querySource
for this example.)