【问题标题】:generic repository EF4 CTP5 getById通用存储库 EF4 CTP5 getById
【发布时间】:2011-03-02 10:41:48
【问题描述】:

我有一个通用存储库,我正在尝试添加一个 GetById 方法,如下所示 C# LINQ to SQL: Refactoring this Generic GetByID method

问题是我的存储库不使用 System.Data.Linq.DataContext 相反,我使用 System.Data.Entity.DbContext

所以我在尝试使用时遇到错误

Mapping.GetMetaType

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

如何在 CTP5 中实现通用 GetById 方法?我应该在我的存储库中使用 System.Data.Entity.DbContext。

这是我的存储库类的开始

  public class BaseRepository<T> where T : class
    {

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

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

        }

【问题讨论】:

    标签: entity-framework generics repository-pattern entity-framework-ctp5


    【解决方案1】:

    最基本的方法很简单

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

    如果您知道所有实体都有定义类型的称为 Id 的主键(在 DB 中不必称为 Id,但它必须映射到属性 Id),您可以简单地使用:

    public interface IEntity
    {
      int Id { get; }
    }
    
    public class BaseRepository<T> where T : class, IEntity
    {
      ...
    
      public T GetById(int id)
      {
        _set.Find(id);
      }
    }
    

    如果数据类型并不总是相同,您可以使用:

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

    您也可以简单地使用:

    public class BaseRepository<TEntity, TKey> where TEntity : class
    {
      ...
    
      public TEntity GetById(TKey id)
      {
        _set.Find(id);
      }
    }
    

    【讨论】:

    • 太好了,感谢您解释许多方法。除了 _set.FindBy 之外,它们似乎都工作正常我在 System.Data.Entity.DBSet 上找不到这个方法
    • 是错字:) 应该是Find
    • @Ladislav Mrnka:在您的第一个示例中,您向 GetById 方法提供 params object[] 键,如果有 2 个字段作为主键,您如何在查找每个键中映射到相关领域?
    • @Noar: Find 在 DbContext API (EFv4.1) 中只需接受 params object[],因此您只需按照实体上定义的正确顺序发送参数。
    • @Ladislav Mrnka:Find 如何知道哪个对象对应哪个键?
    【解决方案2】:

    试试这个

        public virtual T GetByID(object id)
        {
    
            // Define the entity key values.
            IEnumerable<KeyValuePair<string, object>> entityKeyValues =
                new KeyValuePair<string, object>[] { 
                new KeyValuePair<string, object>("Id", id) };
    
            string qualifiedEntitySetName = _context.DefaultContainerName + "." + typeof(T).Name;
            EntityKey key = new EntityKey(qualifiedEntitySetName, entityKeyValues);
    
            return (T)_context.GetObjectByKey(key);           
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 2011-07-15
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      相关资源
      最近更新 更多