Skip to main content
 首页 » 编程设计

c#之构建通用存储库示例

2024年02月23日16yyy_WW

你好,我正在尝试在 linq2sql 之上构建一个通用存储库。我有通用存储库的接口(interface):

 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 个类,“Car”和“House”,现在我想为汽车创建一个专门的存储库:

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<> 的参数。 .