当前位置:  开发笔记 > 后端 > 正文

MVC 6 EF7 RC1创建多个dbcontexts

如何解决《MVC6EF7RC1创建多个dbcontexts》经验,为你挑选了1个好方法。

我试图弄清楚如何在EF7 RC1中创建第二个DB上下文.在过去,我可以使用带有:base("connectionName")的构造函数,但这似乎不再是一个选项,因为它说不能将字符串转换为System.IServiceProvider.

我的第二个上下文代码如下:

public class DecAppContext : DbContext
    {

        public DecAppContext()
          //  :base("DefaultConnection")
        {

        }
        public DbSet VignetteModels { get; set; }
        public DbSet Result { get; set; }
    }
}

在我的config.json中,我指定了连接:

"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-xxxxx...;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  }

在我的启动的配置服务部分中,我添加了两个上下文:

services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]))
                .AddDbContext(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

applicationDB上下文工作正常,因为我可以创建用户并登录而不会出现问题

但是,当我尝试通过以下方式访问控制器中的其他上下文时:

private DecAppContext db = new DecAppContext();
var vignette = db.VignetteModels.SingleOrDefault(v => v.CaseId == vid);

我收到错误:

没有配置数据库提供程序.在设置服务时,通过在DbContext类或AddDbContext方法中覆盖OnConfiguring来配置数据库提供程序.

EF7 RC1中具有多个数据库上下文并访问它们的任何工作示例都将非常受欢迎.



1> Oleg..:

首先,我会向您推荐GitHub上的EntityFramework维基上的文章.本文介绍了许多定义方法DbContext,它们引用了一部分appsettings.json.我个人更喜欢使用[FromServices]属性的方式.

代码可以是以下内容:

首先,您定义appsettings.json了以下内容

{
  "Data": {
    "ApplicationDbConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ApplicationDb;Trusted_Connection=True;MultipleActiveResultSets=true",
    "DecAppDbConnectionString": "Server=Server=(localdb)\\mssqllocaldb;Database=DecAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

您在其中定义两个连接字符串.

声明类秒DecAppContext,并ApplicationDbContext具有DbContext作为基类.最简单的形式就是

public class ApplicationDbContext : DbContext
{
}
public class DecAppContext : DbContext
{
}

没有任何DbSet属性.

第三步.您Microsoft.Extensions.DependencyInjection用来注入数据库上下文.要做到这一点,你需要包括Startup.cs类似的东西

public class Startup
{
    // property for holding configuration
    public IConfigurationRoot Configuration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
        // save the configuration in Configuration property
        Configuration = builder.Build();
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options => {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext(options => {
                options.UseSqlServer(Configuration["Data:ApplicationDbConnectionString"]);
            })
            .AddDbContext(options => {
                options.UseSqlServer(Configuration["Data:DecAppDbConnectionString"]);
            });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...
    }
}

硒创建两个DbContext(DecAppContextApplicationDbContext)使用配置"Data:DecAppDbConnectionString""Data:ApplicationDbConnectionString".

现在我们可以在控制器中使用上下文.例如

[Route("api/[controller]")]
public class UsersController : Controller
{
    [FromServices]
    public ApplicationDbContext ApplicationDbContext { get; set; }

    [FromServices]
    public DecAppContext DecAppContext { get; set; }

    [HttpGet]
    public IEnumerable Get() {
        var returnObject = new List();

        using (var cmd = ApplicationDbContext.Database.GetDbConnection().CreateCommand()) {
            cmd.CommandText = "SELECT Id, FirstName FROM dbo.Users";
            if (cmd.Connection.State != ConnectionState.Open)
                cmd.Connection.Open();

            var retObject = new List();
            using (var dataReader = cmd.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    var dataRow = new ExpandoObject() as IDictionary;
                    for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++)
                        dataRow.Add(
                            dataReader.GetName(iFiled),
                            dataReader.IsDBNull(iFiled) ? null : dataReader[iFiled] // use null instead of {}
                        );

                    retObject.Add((ExpandoObject)dataRow);
                }
            }
            return retObject;
        }
    }
}


或使用async/await相同:

[Route("api/[controller]")]
public class UsersController : Controller
{
    [FromServices]
    public ApplicationDbContext ApplicationDbContext { get; set; }

    [FromServices]
    public DecAppContext DecAppContext { get; set; }

    [HttpGet]
    public async IEnumerable Get() {
        var returnObject = new List();

        using (var cmd = ApplicationDbContext.Database.GetDbConnection().CreateCommand()) {
            cmd.CommandText = "SELECT Id, FirstName FROM dbo.Users";
            if (cmd.Connection.State != ConnectionState.Open)
                cmd.Connection.Open();

            var retObject = new List();
            using (var dataReader = await cmd.ExecuteReaderAsync())
            {
                while (await dataReader.ReadAsync())
                {
                    var dataRow = new ExpandoObject() as IDictionary;
                    for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++)
                        dataRow.Add(dataReader.GetName(iFiled), dataReader[iFiled]);

                    retObject.Add((ExpandoObject)dataRow);
                }
            }
            return retObject;
        }
    }
}


可以public ApplicationDbContext ApplicationDbContext { get; set; }使用属性声明属性[FromServices],ASP.NET从注入的上下文中初始化它ConfigureServices.以同样的方式,您可以DecAppContext在需要时使用第二个上下文.

上面的代码示例将SELECT Id, FirstName From dbo.Users在数据库上下文中执行,并返回表单中的JSON数据[{"id":123, "firstName":"Oleg"},{"id":456, "firstName":"Xaxum"}].从属性名称的转换Id,并FirstNameidfirstName自动使用,因为序列化过程中完成AddJsonOptionsConfigureServices.

更新:我必须参考公告.下一版本的MVC(RC2)将需要更改上面的代码以[FromServices]用作附加参数(Get()例如方法)而不是使用公共属性[FromServices] public ApplicationDbContext ApplicationDbContext { get; set; }.需要删除属性ApplicationDbContext并向Get()方法添加其他参数:public async IEnumerable Get([FromServices] ApplicationDbContext applicationDbContext) {...}.这样的改变很容易完成.请参阅此处以及MVC演示示例中的更改示例:

[Route("api/[controller]")]
public class UsersController : Controller
{
    [HttpGet]
    public async IEnumerable Get(
                     [FromServices] ApplicationDbContext applicationDbContext,
                     [FromServices] DecAppContext decAppContext)
    {
        var returnObject = new List();

        // ...  the same code as before, but using applicationDbContext 
        // and decAppContext parameters instead of ApplicationDbContext
        // and DecAppContext properties
    }

推荐阅读
TXCWB_523
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有