开发者

C# Respository interface with select by id method using generics?

开发者 https://www.devze.com 2023-02-16 05:05 出处:网络
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 t

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 t开发者_运维问答hat 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.)


I generally just have:

public interface IRepository<T>
{
    ...
    T Load(object id);
}

I'd prefer to standardize on using the same type (int) for all primary keys, but if that's not possible, I'd use object and avoid the added complexity of a second generic parameter.


since TE is a generic class you can't do that .

you have to limit this TE generic to implement an interface that has property called [Id]

interface MainInterface
{
    Int ID{get;}
}

and in Reporsitory  :
public interface IRepository<TE, TC>  : where TE is MainInterface
    {
        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();

    }
0

精彩评论

暂无评论...
验证码 换一张
取 消