C#Entity Framework核心和存儲庫

entity-framework-core repository-pattern

讓我的存儲庫檢索信息時遇到一些問題 - 不斷返回null。任何想法都會受到讚賞 - 對此我不熟悉並自學。

庫:

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

我假設您沒有使用依賴注入...如果是這樣,您只需要為您的Controller創建一個構造函數,該構造函數將CustomerRepository作為參數:

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

如果您沒有配置數據庫上下文,請查看: https//docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html這將啟用依賴注入。您需要為存儲庫執行的所有操作都要使用

services.AddScoped<ICustomerRepository,
    CustomerRepository>();

我認為刪除Repository類中的ToList()並刪除Controller中的Cast List<Customer>並使用ToList()代替它ToList()如果確實需要)。因為如果你在視圖中使用它,那麼也可以使用ienumerable。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow