,c#,repository-pattern,generic-collections"/>

首页 > 解决方案 > 在存储库模式中通过 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 idExpression<Func<T, bool>> predicate

标签: c#repository-patterngeneric-collections

解决方案


您不需要所有的转换,绝对不需要字符串转换,因为首先是TKey== TKey,其次,并非所有底层商店都可以应用这些转换。

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

CS0019:运算符==不能应用于类型为TKeyTKey

为了让 C# 知道它可以比较两个TKeys,您需要约束TKeyIEquatable<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));
    }
}

推荐阅读