Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

entity framework - generic repository EF4 CTP5 getById

I have a generic repository an I am trying to add a GetById method as shown here C# LINQ to SQL: Refactoring this Generic GetByID method

The problem is my repository does not use System.Data.Linq.DataContext instead I use System.Data.Entity.DbContext

So I get errors where I try to use

Mapping.GetMetaType

and

return _set.Where( whereExpression).Single();

How can I implement a generic GetById method in CTP5? Should I be using System.Data.Entity.DbContext in my Repository.

Here is the start of my repository class

  public class BaseRepository<T> where T : class
    {

        private DbContext _context;
        private readonly DbSet<T> _set;

        public BaseRepository()
        {
            _context = new MyDBContext();
            _set = _context.Set<T>();

        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The most basic approach is simply

public T GetById(params object[] keys)
{
  _set.Find(keys);
}

If you know that all your entities have primary key called Id (it doesn't have to be called Id in DB but it must be mapped to property Id) of defined type you can use simply this:

public interface IEntity
{
  int Id { get; }
}

public class BaseRepository<T> where T : class, IEntity
{
  ...

  public T GetById(int id)
  {
    _set.Find(id);
  }
}

If data type is not always the same you can use:

public interface IEntity<TKey>
{
  TKey Id { get; }
}

public class BaseRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>
{
  ...

  public TEntity GetById(TKey id)
  {
    _set.Find(id);
  }
}

You can also simply use:

public class BaseRepository<TEntity, TKey> where TEntity : class
{
  ...

  public TEntity GetById(TKey id)
  {
    _set.Find(id);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...