代码之家  ›  专栏  ›  技术社区  ›  Hary

在存储库模式中按TKey查找实体<T,TKey>

  •  0
  • Hary  · 技术社区  · 6 年前

    Repository Pattern ,我正在尝试通过 TKey . 我想找到比较的方法 具有 int

    public interface IRepository<T, TKey>
    {
        T GetById(TKey id);
    }
    
    public class Repository<T, TKey> : IRepository<T, TKey> where T : class, IEntity<TKey>
    {
        private List<T> _context;
    
        public Repository(List<T> context)
        {
            _context = context;
        }
    
        public T GetById(TKey id)
        {
            return _context.Single(m => m.Id == (TKey)id);
        }
    }
    

    对于 TKey键

    public interface IEntity<TKey>
    {
        TKey Id { get; set; }
    }
    
    public class TestEntity : IEntity<int>
    {
        public int Id { get; set; }
    
        public string EntityName { get; set; }
    }
    

    var list = new List<TestEntity>();
    
    list.Add(new TestEntity{ Id = 1 , EntityName = "aaa" });
    list.Add(new TestEntity{ Id = 2 , EntityName = "bbb" });
    
    var repo = new Repository<TestEntity, int>(list);
    var item = repo.GetById(1);
    
    Console.WriteLine(item);
    

    我可能不是在正确的方向与铸造下面的方式,但尝试和运行错误。

    public T GetById(TKey id)
    {
        return _context.Single(m => (object)m.Id == Convert.ChangeType(id, typeof(TKey));
    }
    

    [System.InvalidOperationException:序列不包含匹配元素]

    如何在不改变 TKey id Expression<Func<T, bool>> predicate

    1 回复  |  直到 6 年前
        1
  •  2
  •   CodeCaster    6 年前

    你不需要所有的铸造,绝对没有字符串转换,因为首先也是最重要的 TKey == TKey键 其次,并非所有底层存储都能应用这些转换。

    您需要研究初始代码给出的实际编译器错误:

    CS0019:操作员 == 不能应用于类型为的操作数 TKey键

    TKey键 s、 你需要约束 IEquatable<TKey> .Equals() :

    public class Repository<T, TKey> : IRepository<T, TKey>
        where T : class, IEntity<TKey>
        where TKey : IEquatable<TKey>
    {
        private List<T> _context;
    
        public Repository(List<T> context)
        {
            _context = context;
        }
    
        public T GetById(TKey id)
        {
            return _context.Single(m => m.Id.Equals(id));
        }
    }