C# Entity Framework 核心和存储库

C# Entity Framework Core & 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();
    }

控制器:

   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();
    }

}

我让 efc 创建的 MasterContext:

 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; }
}

我认为您需要创建 Context 和 Repository 的实例。所以在你的控制器中你需要这样的东西:

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

我假设您没有使用依赖注入...如果是这样,您只需要为您的控制器创建一个以 CustomerRepository 作为参数的构造函数:

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

如果您没有配置数据库上下文,请查看此处:https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html 这将使您能够进行依赖注入。您需要为存储库做的所有事情都是使用

services.AddScoped<ICustomerRepository,
    CustomerRepository>();

而且我认为删除存储库 class 中的 ToList() 并删除控制器中的 Cast List<Customer> 并使用 ToList() 可能会更好,如果真的很需要。因为如果您在视图中使用它,ienumerable 也可以工作。