使用控制器实现存储库

时间:2016-08-18 13:39:17

标签: c# entity-framework controller repository entity-framework-core

我正在教自己c#sharp并使用Entity Framework Core和存储库模式。我设法让EFcore在本地sql保存等方面正常工作。我现在正试图通过存储库来实现这一点。 我为每种方法创建了一个IrepositoryFile和Repository:

 public interface ICustomerRepository
{
    IEnumerable<Customer> GetCustomers();
    Customer GetCustomerById(int customerId);
    void InsertCustomer(Customer customer);
    void DeleteCustomer(int customerId);
}
 public class CustomerRepository : ICustomerRepository
{
    private masterContext context;

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

    public void InsertCustomer(Customer customer)
    {
        context.Customer.Add(customer);
        context.SaveChanges();
    }

    public void DeleteCustomer(int customerId)
    {
        //Customer c = context.Customer.Find(customerID);
        var cc = context.Customer.Where(ii => ii.CustomerId == customerId);
        context.Remove(cc);
        context.SaveChanges();
    }

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

我现在正在努力让它工作并采取下一步将其放入控制器以显示在html页面上。

这是我尝试通过控制器实现存储库:

    using System.Collections.Generic;
using CustomerDatabase.Core.Interface;
using CustomerDatabase.Core.Models;
using Microsoft.AspNetCore.Mvc;

namespace CustomerDatabase.Core.Controllers
{
    public class CustomerController2 : Controller
    {
        private readonly ICustomerRepository _repository = null;
        public CustomerController2()
        {
            this._repository = new CustomerRepository();
        }
        public CustomerController2(ICustomerRepository repository)
        {
            this._repository = repository;
        }

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

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

        public ActionResult Insert(Customer obj)
        {
            _repository.InsertCustomer(obj);
            _repository.Save();
            return View();
        }

        public ActionResult Edit(int id)
        {
            Customer existing = _repository.GetCustomerById(id);
            return View(existing);
        }

    }
}

但是我收到了这个错误:

Multiple constructors accepting all given argument types have been found in type 'CustomerDatabase .Core. Controllers. CustomerController. There should only be one applicable constructor.

请有人帮助= - 说清楚,因为我不引用所有技术术语

1 个答案:

答案 0 :(得分:1)

我认为你的问题在于这两个构造函数:

public CustomerController2()
{
    this._repository = new CustomerRepository();
}

public CustomerController2(ICustomerRepository repository)
{
    this._repository = repository;
}

从一点点阅读看起来内置的解析器看起来不支持暴露多个构造函数的类型。请参阅this linked question