2016-08-18 2 views
0

정보를 검색하기 위해 저장소를 가져 오는 데 몇 가지 문제가 있습니다. 어떤 생각이라도 감사 할 것입니다.C# Entity Framework 핵심 및 저장소

저장소 :

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

아마도이 문제는 해결되지 않지만 ienumerable을 반환 할 때 tolist를 사용하는 이유는 무엇입니까? 그것은 자원 낭비입니다.) –

+0

그리고 나는 당신이 방법을 사용할 때 그것을 던지기보다 당신이 깨달았습니다. 그건 트리플 캐스팅이다. –

+0

아 맞다. CustomerRepository의 인스턴스를 생성 할 필요가 없다. Depenency injection을 사용합니까? –

답변

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()을 저장소 클래스의 ToList()을 제거하고 컨트롤러의 캐스트 List<Customer>를 제거하고 사용하는 것이 좋을 수 있다고 생각 필요합니다. 보기에서 ienumerable을 사용하면 ienumerable도 작동 할 수 있기 때문입니다.

+0

고마워요. 그 줄에 뭔가있는 줄 알았지 만 새 masterContect에 문제가 생겼습니다. masterContext.masterContext의 필수 형식 매개 변수 옵션에 해당하는 인수가 없다고 말합니다. 위의 마스터 컨투어를 원본 피드에 포함 시켰습니다 - 도와 주실 수 있습니까? – Webezine

+1

Startup.cs 파일에서 구성 했습니까? –

+0

도움을 주셔서 감사합니다. 올바른 방향으로 나를 지적 했으므로 문제를 해결할 수 있었고 지금은 실제로 작동하는 모델을 가지고 있습니다. 다시 한번 감사드립니다!! – Webezine

관련 문제