С Repository Pattern
я пытаюсь найти сущность по TKey
.Я пытаюсь найти способ сравнить 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);
}
}
Здесь, передавая int
для TKey
public interface IEntity<TKey>
{
TKey Id { get; set; }
}
public class TestEntity : IEntity<int>
{
public int Id { get; set; }
public string EntityName { get; set; }
}
Наконец, Test Client
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));
}
[Система.InvalidOperationException: последовательность не содержит соответствующего элемента]
Как реализовать тот же подход без изменения параметра с TKey id
на Expression<Func<T, bool>> predicate