有一些問題讓我的存儲庫檢索信息 - 保持返回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; }
}
這可能無法解決您的問題,但爲什麼在返回可枚舉時使用tolist?這就是資源的浪費;) –
我意識到你比使用方法時拋棄它。這是一個三重播放 –
哦,是的,你不需要創建一個CustomerRepository的實例。你使用Depenency注射嗎? –