您可以将存储库限制为由您创建的某个基类,比如EntityBase(这应该是抽象的)
public class EntityBase
{
public int Id { get; set;Â }
}
public class Repository<TEntity> : IRepository<TEntity> where TEntity : EntityBase
{
...
}
[Test]
public void Add_AddsEntityToRepository()
{
//arrange
var storageSystem = new StorageSystem {Id = 1, Name = "Storage1"};
var repo = new Repository<EntityBase>(_context);
//act
repo.Add(storageSystem);
_uow.Complete();
//assert
Assert.AreEqual(1, _context.StorageSystems.Count());
}
由于您要通过inherinition确保每个类型至少都有EntityBase的成员,因此不必进一步测试实体类型的继承树(除非您对此有特定的用例)
如果您需要知道基类上的某些方法,但实现依赖于子类,只需将该方法作为基类中的抽象成员并在子类中重写即可。
public class EntityBase
{
public int Id { get; set; }
// sample method that copies member values from other object to current instance
public abstract void CopyProperties(EntityBase other);
}
public class Student : EntityBase
{
public int Id { get; set; }
public override void CopyProperties(EntityBase other)
{
...
}
}