我想要做的事情非常简单 - 我想创建通用存储库,其中泛型是通用基础实体,其中实体上的泛型设置键的类型。迷惑?不要,让我们来看看代码:
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
}
}
是否存在解决此问题的方法?我想避免基本存储库的硬编码密钥类型。我想到的只是写入方法查找为虚拟(或抽象),然后为长键实体,字符串键实体创建特殊存储库,但......这不是解决方案,只是解决方法......