【问题标题】:Generic repository for generic base class and query for find by key通用基类的通用存储库和按键查找查询
【发布时间】:2014-08-12 13:08:26
【问题描述】:

我想要做的非常简单——我想创建通用存储库,其中通用是通用基础实体,其中通用在实体上设置键的类型。迷惑?不说了,看代码吧:

public interface IEntity<TKey>
{
    TKey Id { get; set; }
    DateTime Create { get; set; }
    DateTime? Storno { get; set; }
}

public class Entity<TKey> : IEntity<TKey>
{
    public TKey Id { get; set; }
    public DateTime Create { get; set; }
    public DateTime? Storno { get; set; }
}

public class Repository<TEntity, TKey> : IRepository<TEntity, TKey> 
    where TEntity : Entity<TKey>
{
    protected DbContext context;
    protected DbSet<TEntity> database;

    public TEntity Find(TKey id)
    {
        //return database.SingleOrDefault(f => f.Id == id); // <-- Here is how it should look like
        return database.SingleOrDefault(f => f.Id.Equals(id)); // <-- Here is problem EF cann't work with this construction
    }
}

有解决这个问题的办法吗?我想避免基本存储库的硬编码密钥类型。我刚想到的是将方法 Find 编写为虚拟(或抽象),然后为长键实体、字符串键实体创建特殊存储库,但是……这不是解决方案,而是解决方法……

【问题讨论】:

  • 为什么不重用现有的Find

标签: c# entity-framework generics repository repository-pattern


【解决方案1】:

您可以使用DbSet&lt;T&gt;.Find(params object[] keys) 按键查找实体:

return database.Find(id);

【讨论】:

  • 天啊...我不知道 Find 方法。谢谢你就像魅力一样!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多