构建一个通用的存储库示例
本文关键字:存储 一个 构建 | 更新日期: 2023-09-27 18:16:16
你好,我试图在linq2sql之上构建一个通用存储库。我有一个通用存储库的接口:
public interface IRepository<T> where T : class
{
void Update(T entity);
T CreateInstance();
void Delete(int id);
T Get(int id);
List<T> GetAll();
List<T> GetAll(Func<T, bool> expr);
}
我也有一个实现。现在我已经通过linq2sql连接到我的数据库,并得到2个类,"汽车"answers"房子",现在我想为汽车做一个专门的存储库:
public interface ICarRepository<Car> : IRepository<Car>
{
}
现在我得到错误:The type 'Car' must be a reference type in order to use it as parameter 'T' in the generic type or method 'GenericRepository.Repository.IRepository<T>'
为什么我得到这个错误,这是"Car"类的签名:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Car")]
public partial class Car : INotifyPropertyChanging, INotifyPropertyChanged
{...}
你的界面是错误的,它应该是:
public interface ICarRepository : IRepository<Car>
{
}
错误是您认为您正在"使用"Car
类型,而实际上您正在定义一个名为Car
的泛型参数。由于它不受引用类型的约束,因此不能作为IRepository<>
的a形参使用。
尝试将接口声明更改为
public interface ICarRepository : IRepository<Car> {}
在接口名中不引用Car
类。您正在从泛型接口继承—继承声明是您需要声明该类的唯一地方。