我在教自己c#銳利和玩弄實體框架核心和存儲庫模式。我已經設法讓EFcore正常工作,從本地的sql儲存等工具中獲取信息。我現在試圖通過一個存儲庫來獲得這個工作。 我創建了一個IrepositoryFile和信息庫爲每個方法:實施與控制器的存儲庫
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.
可以請別人幫忙= - 說白了,我不報價把握所有技術術語
你能解釋一下哪些工作不正常嗎? – sr28
那麼我現在需要將接口實現爲一個控制器 - 我不知道該怎麼做。 – Webezine
您是否有機會使用本教程:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and-entity-framework熱媒。如果沒有,那麼它涵蓋了如何在控制器中使用它 – sr28