【发布时间】: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