与
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