2016-08-18 35 views
0

有一些問題讓我的存儲庫檢索信息 - 保持返回null。任何想法,將不勝感激 - 新的這一點,並教我自己。C#實體框架核心和存儲庫

庫:

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

} 

MasterContext,我曾EFC使:

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

這可能無法解決您的問題,但爲什麼在返回可枚舉時使用tolist?這就是資源的浪費;) –

+0

我意識到你比使用方法時拋棄它。這是一個三重播放 –

+0

哦,是的,你不需要創建一個CustomerRepository的實例。你使用Depenency注射嗎? –

回答

1

我認爲你需要創建上下文的您實例和您的存儲庫。因此,在你的控制器,你需要這樣的事:

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

而且我認爲這可能是很好的去除ToList()存儲庫中類和去除演員List<Customer>在你的控制器,並使用ToList()相反,如果這是真的需要。因爲如果你在View中使用它,那麼可枚舉也可以工作。

+0

感謝你 - 我認爲這是沿着這些線,但我現在有新的masterContect問題 - 說沒有任何爭論,因爲對masterContext.masterContext所需的正式paramaeter選項的響應。在原始Feed中包含上面的主要內容 - 你能幫忙嗎? – Webezine

+1

你在Startup.cs文件中配置了它嗎? –

+0

非常感謝您的幫助 - 這表明我朝着正確的方向前進,並且我能夠解決問題,現在有一個工作模式。再一次感謝你!! – Webezine