2016-08-18 12 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 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を返すときにリストを使用するのですか?それはリソースの無駄です;) –

+0

そして私はあなたが方法を使用するときにキャストよりもあなたが実現しました。それはトリプルキャストです –

+0

ああ、そうです。あなたはCustomerRepositoryのインスタンスを作成する必要はありません。あなたはDepenency injectionを使用しますか? –

答えて

1

は、私はあなたコンテキストとあなたのリポジトリのインスタンスを作成する必要があると思う:私はEFC作ってもらいました

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。だからあなたのコントローラであなたはこのような何かする必要があります:

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()を使用することが良いと思います必要です。ビューでそれを使用している場合は、ienumerableも機能する可能性があるためです。

+0

ありがとうございました - 私はそれがそれらの行に沿ったものだと思っていましたが、今は新しいmasterContectに問題があります - masterContext.masterContextの必要な正式なparamaeterオプションに対応する引数はありません。上記のマスターcontectを元のフィードに含めました - お手伝いできますか? – Webezine

+1

Startup.csファイルで設定しましたか? –

+0

助けてくれてありがとうございます - これは正しい方向に私を指摘し、私は問題を解決することができました、そして今は実用的なモデルを持っています。もう一度ありがとう! – Webezine

関連する問題