Answer the question
In order to leave comments, you need to log in
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;
}
}
var context = new DBContext();
Answer the question
In order to leave comments, you need to log in
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question