如何在Generic Repository中传递实体和ID?

时间:2017-02-10 10:56:23

标签: c# generics

public interface IRepository<TEntity, in TID> where TEntity : IAggregateRoot
{
    TEntity Find(TID id);
}

其实施如下:

    public class Repository<TEntity, TID> : IRepository<TEntity, TID> where TEntity : class, IAggregateRoot
{
    public virtual TEntity Find(TID id)
    {
        return _unitOfWork.Session.Get<TEntity>(id);
    }
}

如何在上面的存储库中传递 TID

1 个答案:

答案 0 :(得分:0)

这是一种通用类型。您必须在实例存储库时定义它。对于示例,对于名为Product的实体,其中Idint

var productRepository = new Repository<Product, int>();

// to call a method, you have to pass the TID defined, which is an int 
// and it will return a TEntity, that is a Product.
Product product = productRepository.Find(1);