注入DbContext并使用一个连接执行多个查询

时间:2017-01-31 21:17:43

标签: c# asp.net-core entity-framework-core

我正在使用EF Core和ASP.NET Core:

 public partial class SecurityDBContext : DbContext
 {
      // injecting the DBcontext from the ASP.NET or Bootstrap applicaiton with the required connection string
      public SecurityDBContext(DbContextOptions options) : base(options)
      {

      }
}

这是我的存储库类,我正在注入所需的上下文:

 public class UserRepository : IUserRepository
{
    private SecurityDBContext securityDb;
    private readonly ILogger<UserRepository> _logger;

    public UserRepository(SecurityDBContext securityContext, ILogger<UserRepository> logger)
    {
        securityDb = securityContext;
        _logger = logger;

    }
    public void MultipleQueries(int id)
    {

        var result1= securityDb.Users.Where(u=> u.Id == id).SingleOrDefault();


       //var result2 = securityDb.Table2.Where(...)ToList();
    }

以下是我如何通过家属:

var securityDB = configurationRoot.GetConnectionString("SecurityDatabase");
if (securityDB == null)
   {
       throw new ArgumentNullException("SecurityDatabase ConnectionString");
   }
//EnityDB
    services.AddEntityFrameworkSqlServer().AddDbContext<SecurityCore.Repositories.SecurityDBContext>(options => options.UseSqlServer(securityDB));

假设我在不同的数据库实体上执行结果2和结果3,是为每个查询打开连接的上下文?如果是,那么我如何根据最佳实践避免这种情况并通过一个连接进行查询。

0 个答案:

没有答案