【发布时间】:2016-12-25 11:24:42
【问题描述】:
我正在自学 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.
请有人帮忙=-说清楚,因为我不引用掌握所有技术术语
【问题讨论】:
-
你能准确解释一下什么不起作用吗?
-
好吧,我现在需要将接口实现到控制器中 - 我不知道如何/做什么。
-
您是否有机会使用本教程:codeguru.com/csharp/.net/net_asp/mvc/…。如果没有,那么它将介绍如何在控制器中使用它
-
是的,尝试这样做并按照他们的示例进行操作,但我遇到了问题-在上面进行了修改以提供更多信息。
-
错误消息提及
CustomerDatabase.Core.Controllers.CustomerController,而您提供CustomerDatabase.Core.Controllers.CustomerController2的代码。无法调试缺少的代码。
标签: c# entity-framework controller repository entity-framework-core