2016-08-18 90 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