Webezine
Webezine

Reputation: 456

C# Entity Framework Core & Repository

Having some issues getting my repository to retrieve information - keeps coming back null. Any Thoughts would be appreciated - new to this and teaching myself.

Repository:

 public class CustomerRepository : ICustomerRepository
{
    private masterContext context;

    public CustomerRepository(masterContext context)
    {
        this.context = context;

    }
    public IEnumerable<Customer> GetCustomers()
    {
        return context.Customer.ToList();
    }

    public Customer GetCustomerById(int customerId)
    {
        var result = (from c in context.Customer where c.CustomerId == customerId select c).FirstOrDefault();
        return result;
    }

    public void Save()
    {
        context.SaveChanges();
    }

Controller:

   public class CustomerController : Controller
{
    private readonly ICustomerRepository _repository = null;


    public ActionResult Index()
    {
        var model = (List<Customer>)_repository.GetCustomers();
        return View(model);
    }

    public ActionResult New()
    {
        return View();
    }

}

MasterContext which i had efc make:

 public partial class masterContext : DbContext
{
    public masterContext(DbContextOptions<masterContext> options)
        : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>(entity =>
        {
            entity.Property(e => e.CustomerName).IsRequired();
        });
    }

    public virtual DbSet<Customer> Customer { get; set; }
    public virtual DbSet<Order> Order { get; set; }
}

Upvotes: 0

Views: 1778

Answers (1)

Morris Janatzek
Morris Janatzek

Reputation: 672

I think you need to create instances of you Context and your Repository. So in your Controller you need to something like this:

private masterContext context = new masterContext();
private ICustomerRepository repository = new CustomerRepository(context);

I assume that you're not using Dependency injection ... if so you just need to create a Constructor for your Controller that takes CustomerRepository as argument:

public CustomerController(ICustomerRepository _repository) {
    repository = _repository;
}

If you did not configure your database context, look here: https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html This will than enable you the dependency injection. Everything you than need to do for the Repository is to use

services.AddScoped<ICustomerRepository,
    CustomerRepository>();

And I think it could be good to remove the ToList() in the Repository class and remove the Cast List<Customer> in your Controller and use ToList() instead, if it's really needed. Because if you're using it in the View the ienumerable could also work.

Upvotes: 1

Related Questions