ASP.NET 5、Entity Framework 7和SQL Server 2014 - 多个dbContexts、SQL视图

3
我在Visual Studio 2015中创建了一个解决方案,包括一个Web项目(使用ASP.NET 5 Beta 6 Web应用程序预览模板)和一个Model项目(使用Entity Framework 7 Beta 6)。
我已经能够从SQL Server数据库获取数据并在页面上显示。然后,我想尝试从两个不同的数据库中提取数据,但是在尝试使用多个dbContext时遇到了问题。
在Startup.cs中,我添加了EF服务并添加了一个dbContext,这很好用。但我不知道如何添加多个...下面的代码是我尝试添加另一个的方式,但第二个AddDbContext似乎只是覆盖了第一个。
我还遇到了另一个与此有关的问题..我无法从SQL视图中获取数据。我确认该视图包含数据,但当我编写一个WebAPI方法从该视图获取数据时,响应中什么也没有。在以前使用EF6的项目中,我没有问题对视图进行建模并从中检索数据。
总结我的问题:
1. 如何在使用EF7的ASP.NET 5 Web项目中设置多个dbContext? 2. 如何在EF7中对SQL Server视图进行建模?
Startup.cs:
public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
    // Setup configuration sources.
    var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
    // Register Entity Framework
    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<MyContextA>(options =>
            options.UseSqlServer(Configuration["Data:DefaultConnection:AConnectionString"])
        )
        .AddDbContext<MyContextB>(options =>
            options.UseSqlServer(Configuration["Data:DefaultConnection:BConnectionString"])
        );

    services.AddMvc();
}

config.json

{
  "Data": {
    "DefaultConnection": {
      "AConnectionString": "data source=xxxxxxx;initial catalog=xxxxxxxx;Uid=xxxxxxxxx;Pwd=xxxxxx;",
      "BConnectionString": "data source=xxxxxxx;initial catalog=xxxxxxxx;Uid=xxxxxxxxx;Pwd=xxxxxx;"
    }
  },
  "EntityFramework": {
    "MyContextA": {
      "ConnectionStringKey": "Data:DefaultConnection:AConnectionString"
    },
    "MyContextB": {
      "ConnectionStringKey": "Data:DefaultConnection:BConnectionString"
    }
  }
}

MyContextA.cs

public class MyContextA : DbContext
{
    public MyContextA (DbContextOptions options) : base(options) { }
    public DbSet<Product> Product { get; set; }
    public DbSet<Some_View> Some_View { get; set; }
}

MyContextB.cs

public class MyContextB : DbContext
{
    public MyContextB (DbContextOptions options) : base(options) { }
    public DbSet<Customer> Customer { get; set; }
}

Product.cs

public class Product
{
    [Key]
    public int ID { get; set; }
    public int Name { get; set; }
}

Some_View.cs

public class Some_View
{
    public int SomeField { get; set; }
    public int AnotherField { get; set; }
}

TestController.cs

[Route("api/[controller]")]
public class TestController : Controller
{
    private readonly MyContextA _dbContext;

    // Constructor
    public TestController(MyContextA dbContext)
    {
        _dbContext = dbContext;
    }

    // GET: api/values
    [HttpGet]
    public IEnumerable<Some_View> Get()
    {
        var data = _dbContext.Some_View;
        return data;
    }
}

我能使用一个dbContext和常规表,比如上面的Product,使一切正常运作。但是当我尝试使用视图时,无法获取数据;当我使用多个contexts时,第二个context会覆盖第一个。


“事情为什么不能正常工作?”你期望看到的行为是什么?错误信息?等等。 - natemcmaster
当我使用视图时,没有错误消息,但响应中没有数据。此外,如果我在Startup.cs中添加两个dbContexts,则会使用第二个上下文而不是第一个。 - Jerms
2个回答

2
尝试将您的DbContext构造函数更改为以下内容:
public MyContextA (DbContextOptions<MyContextA> options) : base(options) { }
public MyContextB (DbContextOptions<MyContextB> options) : base(options) { }

试试调用 ToList() 方法

return data.ToList();

每一个问题都可能是你想要在EF和MVC存储库上提交的错误。请点击EFMVC链接提交。

ToList() 抛出异常,而且编辑构造函数似乎没什么影响。感谢建议,也会查看 EF 和 MVC 仓库。 - Jerms
看起来EF7还不支持视图 - Jerms
它支持视图。在查询期间,它们与表没有任何区别,如果它们是可更新的视图,在更新期间也没有区别。 - bricelam
通过为DbContextOptions应用特定类型,解决了我的问题。没有DbContextOptions<MyContextA>和DbContextOptions<MyContextB>,MyContextB会在StartUp.cs中覆盖MyContextA。 - MasterWil

0
如果有人需要帮助,这个问题在.NET Core和EF Core 1.0.0中已经不再是问题了。以下是我在Web API Startup.cs中注册每个dbcontext的方法。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddDbContext<Context1>(options => options.UseSqlServer(Configuration["ConnectionStrings:Connection1"]));
    services.AddDbContext<Context2>(options => options.UseSqlServer(Configuration["ConnectionStrings:Connection2"]));
    // ...
}

appsettings.DEVELOPMENT.json

{
  "ConnectionStrings": {
    "Connection1": "[connection string here]",
    "Connection2": "[connection string here]",
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接