c# - 在存储库模式中通过 TKey 查找实体
问题描述
使用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; }
}
最后,测试客户端
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
解决方案
您不需要所有的转换,绝对不需要字符串转换,因为首先是TKey
== TKey
,其次,并非所有底层商店都可以应用这些转换。
您需要研究初始代码给出的实际编译器错误:
CS0019:运算符
==
不能应用于类型为TKey
和TKey
为了让 C# 知道它可以比较两个TKey
s,您需要约束TKey
并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));
}
}
推荐阅读
- android - 如何只获得最大数量的指针
- javascript - 从初始化定位节点
- sql - 如果缺少 1 个级别,则获取超级父列表或显示父级
- python - 如何让 python 脚本再次重复 x 次?
- python - 解密大文件时 MAC 检查失败
- python - 为什么我不能让我的输出数据帧转换为 csv?AttributeError:“NoneType”对象没有属性“to_csv”
- html - 如何在圆形图像周围放置多色边框?
- excel - VBA代码根据单元格范围内的单元格值显示消息
- c# - 配置 NLog 以使用管理标识令牌将日志写入 Azure SQL 服务器
- java - Selenium WebDriver 是同步还是异步打开多个选项卡?