2016-08-12 10 views
0

データを照会できるようにクラスを作成しました。私はコントローラクラスのデータコンテキストでそれを行う場合、私が作成したクラスでそれを行う場合、それはnullエラーをスローします。これは、次のエラースロー: Microsoft.Extensions.DependencyInjection.Abstractions.dllをしかし、私のスタートアップコンフィギュレーションユーザーコード で処理されていなかった。c#asp.net core。別のクラスからdatacontextにアクセスするにはどうすればいいですか?

public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddApplicationInsightsTelemetry(Configuration); 

     services.AddDbContext<Abstractor_DataContext>(options => 
      options.UseSqlServer(Configuration.GetConnectionString("ApplicationDatabase"))); 

     //services.AddTransient(typeof(Abstractor_DataContext)); 


     //Register your filter as a service (Note this filter need not be an attribute as such) 
     services.AddTransient<AppExceptionFilterAttribute>(); 

     services.AddMvc(); 
    } 

私のクラスの機能が

using Microsoft.Extensions.DependencyInjection; 
    public static IList<ApplicationInfo> TestDb() 
     { 
      //var options = _serviceProvider.GetService<Abstractor_DataContext>(); 
      using (var context = _serviceProvider.GetService<Abstractor_DataContext>()) 
      { 
       return context.ApplicationInfo.ToList(); 
      } 
     } 

VARのDataContextにアクセスするにはコンテキストはnullです。私は何が欠けていますか?私はDIを学ぶのが遅いです。新しいDBベースのASP.netコアプロジェクトのofficial documentationあたりとして

+0

DbContextを入力として使用していないため、DbContextオブジェクトを提供することはできません。 – skjoshi

+0

この 'TestDb'メソッドはいつ使用していますか?このメソッドを呼び出した時点でデータコンテキストが登録されている場合は、それが機能するはずです。しかし、例では、データベース 'Seed'の間にこれを呼び出すと動作しません。 –

+0

エフライム、私はそれを私のコントロールで呼んでいます。 [HTTPGET] [ルート( "GetTestDb")] 公共のIList <にApplicationInfo> GetTestDb(INT番号) {リターンDataAccessServices.TestDb(); // _ context.ApplicationInfo.ToList()。 } – inavnacorp

答えて

2

、まず、あなたのモデルとDbContextを作成する必要があります。

using Microsoft.EntityFrameworkCore; 
using System.Collections.Generic; 

namespace EFGetStarted.AspNetCore.NewDb.Models 
{ 
    public class BloggingContext : DbContext 
    { 
     public BloggingContext(DbContextOptions<BloggingContext> options) 
      : base(options) 
     { } 

     public DbSet<Blog> Blogs { get; set; } 
     public DbSet<Post> Posts { get; set; } 
    } 

    public class Blog 
    { 
     public int BlogId { get; set; } 
     public string Url { get; set; } 

     public List<Post> Posts { get; set; } 
    } 

    public class Post 
    { 
     public int PostId { get; set; } 
     public string Title { get; set; } 
     public string Content { get; set; } 

     public int BlogId { get; set; } 
     public Blog Blog { get; set; } 
    } 
} 

その後、依存性注入を使用してコンテキストを登録します。

public void ConfigureServices(IServiceCollection services) 
     { 
      var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;"; 
      services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection)); 

データベースの移行を使用してデータベースを作成します。コンストラクタを使用してコントローラを作成し、パラメータをコンテキストの1つとして使用します(コンストラクタパラメータのBloggingContext contextを参照)。

using EFGetStarted.AspNetCore.NewDb.Models; 
using Microsoft.AspNetCore.Mvc; 
using System.Linq; 

namespace EFGetStarted.AspNetCore.NewDb.Controllers 
{ 
    public class BlogsController : Controller 
    { 
     private BloggingContext _context; 

     public BlogsController(BloggingContext context) 
     { 
      _context = context; 
     } 

     public IActionResult Index() 
     { 
      return View(_context.Blogs.ToList()); 
     } 

     public IActionResult Create() 
     { 
      return View(); 
     } 

     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public IActionResult Create(Blog blog) 
     { 
      if (ModelState.IsValid) 
      { 
       _context.Blogs.Add(blog); 
       _context.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 

      return View(blog); 
     } 

    } 
} 

どのクラスでもDbContextを使用することは、コントローラで使用することと同じです。 Dependencyインジェクタにクラスを登録する必要があります。方法はConfigureServicesです。 This page from official docsに詳細が記載されています。

services.AddScoped<ICharacterRepository, CharacterRepository>(); 
services.AddTransient<IOperationTransient, Operation>(); 
services.AddScoped<IOperationScoped, Operation>(); 
services.AddSingleton<IOperationSingleton, Operation>(); 
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty)); 
services.AddTransient<OperationService, OperationService>(); 
+1

OPはコントローラの外部のコンテキストにアクセスする必要があります。そうではありません。 –

+0

サンジュさんに感謝します。私はEFを使ってモデルを作成しました。あなたが提供した例のように、コントローラクラスのデータコンテキストにアクセスするとすべて動作しますが、コントローラではない別のクラスでデータコンテキストを使用しようとすると、エラーがスローされます。ドキュメントを読むと、Iscontviceを使ってdbcontextサービスを呼び出し、Microsoft拡張DIパッケージを追加することができますが、これはまだエラーをスローし、コンテキストはnullと言います。 – inavnacorp

+0

サービスクラス(コントローラークラスの外部)でDIを使用してDbContextを使用するように答えを更新しました。 – skjoshi

関連する問題