本文介绍了从通用存储库派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用存储库类,见下图,这是用来执行常见的数据访问功能,即添加,GetByID等。

I have a Generic Repository class, see below, which is used to perform common Data Access functions, ie, Add, GetByID etc.

    public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
    {
    internal GolfEntities context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(GolfEntities context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }



我想创建一个从这个通用库类派生另一个仓库类,所以我可以进行哪些不属于通用库类的其他功能,比如,获得了用户的全名。

I would like to create another Repository class that derives from this Generic Repository class so that I can carry out other functions which do not belong to the Generic Repository class, such as, get a users full name.

我创建了一个叫做UserRepository AA级,请参阅下面,从通用存储库派生,但是,我不断收到一个错误,当我编译:

I have created a a class called UserRepository, see below, which derives from the Generic Repository, however, I keep getting an error when I compile:

&Repository.GenericRepository LT;用户>不包含一个构造函数0参数

Repository.GenericRepository< User> does not contain a constructor that takes 0 arguments

public class UserRepository : GenericRepository<User>, IUserRepository
{

    internal GolfEntities _context;

    public UserRepository() : base() { }

    public UserRepository(GolfEntities context)
    {
        _context = context;
    }

    public string FullName()
    {
        return "Full Name: Test FullName";
    }


}



有谁知道如何解决这个问题?

Does anyone know how to fix this?

任何帮助将非常感激。

感谢。

推荐答案

您应该从派生资源库中删除默认的构造函数:

You should remove the default constructor from your derived repository:

public UserRepository() : base() { }

由于您的基础库类没有按'吨有一个参数的构造函数调用基地()没有意义。你也不必重复同样的逻辑在派生构造函数中的基地之一。你只能调用它:

Since your base repository class doesn't have a parameterless constructor calling base() doesn't make sense. Also you don't need to repeat the same logic in your derived constructor as in the base one. You could only invoke it:

public class UserRepository : GenericRepository<User>, IUserRepository
{
    public UserRepository(GolfEntities context): base(context)
    { 

    }

    public string FullName()
    {
        return "Full Name: Test FullName";
    }
}

这篇关于从通用存储库派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:16