简体   繁体   中英

Create a new repository or use existing one?

I'm working with a database for my first time. It's holds products and descriptions, etc. Now I want to push user data to the database. Do I put my methods in the same repository file that I've already created, or do I make a new one? My current repository is called EFRepository, and the interface file is IEFRepository. Are these names arbitrary? Can I make new files and name them whatever I want? Or should I just continue working with these files? Thanks!

The short answer is yes, use the same files. That said, you'll likely not need to add new methods to it. You're probably using either MVC or WebAPI. If so, you'll have separate files that have the methods for each Entity (I assume the EF stands for Entity Framework).

You'll have files with names like 'ProductController.cs' that have a 'GetProducts' and 'PostProduct' and whatever else you need to do to products. These files will have instances of the database context, whether by instantiating them in the file or using 'dependency injection', something like:

using IEFRepository;

class ProductController : ApiController 
{
    IEFRepository<Product> _prodRepo;

    public ProductController(
        IEFRepository<Product> prodRepo
    )
    {
        _prodRepo = prodRepo;
    }

    [HttpGet]
    public List<Product> GetProducts() => _prodRepo.Get().ToList();

}

The .Get() is from the repository class you've already created, which should then work for every table in your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM