V
V
VanilaSpirit2021-03-09 18:44:28
ASP.NET
VanilaSpirit, 2021-03-09 18:44:28

How to call/initialize a repository in a model class?

I have two classes in Model>Cars.cs:

public class Cars{
    public string Name { get; set; }
    public string Number { get; set; }
}


public static class CarsHelper
{
    public static string GetOrAddCarNumber(string name)
    {
        var context = new DBContext();
        var car = context.Cars.FirstOrDefault(x => x.Name == name);
        if(car == null)
            {
                context.Cars.Add(new Cars()
                {
                    Name = name,
                    Number = ""
                });
            }

            return Cars.Number;
    }
}


I used to write But I started to study the repository pattern and rewrite the project for it, and even I don’t understand how to do it right) And is it generally right to do this? In CarsHelper, I have a couple of methods where it needs to be used. var context = new DBContext();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-03-09
@VanilaSpirit

You make the CarsRepository class by type

public class CarsRepository
{
    private readonly DbContext _dbContext;
    public CarsRepository(DbContext dbContext) => _dbContext = dbContext;

    public async Task<string> GetOrAddCarNumberAsync(string carName)
    {
        var car = await _dbContext.Cars.FirstOrDefaultAsync(x => x.Name == name);
        if(car == null)
        {
            car = new Car {
                    Name = name,
                    Number = ""
            };
            _dbContext.Cars.AddAsync(car);
            await _dbContext.SaveChangesAsync():
         }
         return car.Number;
    }
}

But in general, EF already implements the Repository pattern for you, so it will be enough for you to write only extension methods for DbSets

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question