How to work with several databases using entity framework core

1

I have a doubt, it will be possible to work with several databases in an asp.net core solution using entity framework core, what happens is that I have already created the databases and the database first because I understand it a little, what I can not find how to do is that I have some screens developed in php and there one directly works with the sql and can handle more easily using one base or another, but here in the work you want to migrate to asp.net core and use .net core to make it cross-platform, but since entity framework core should be used for the management of the database, I do not know how to use in a single solution or application, all the databases that we use with php, you could guide me a bit about this, thanks.

    
asked by JasRey 06.11.2017 в 22:16
source

1 answer

0

A simple example. We have a DB for Workers and one for Entities, and in the Trabjadores driver I want a list of Entities to show.

The first step is to add a connection string for each BD you use. This is shown in appsettings.json

{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=Identity;Trusted_Connection=True;MultipleActiveResultSets=true",
"TrabajadoresConnection": "Server=(localdb)\mssqllocaldb;Database=Trabajadores;Trusted_Connection=True;MultipleActiveResultSets=true",
"EntidadesConnection": "Server=(localdb)\mssqllocaldb;Database=Entidades;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Warning"
  }
}

}

As you can see in this example I am using 3 Databases, Identity and its connection string is called DefaultConnection, Trabajadores TrabajadoresConnection and Entidades EntidadesConnection. To the connection string you can put the name you want, the other parameters you must specify depending on the type of connection you have and your BD, in my case I am using localdb which is included by default in Visual Studio.

The other step is the Database Context, in my case create one for each BD. You create a class in the Data directory of your project similar to this:

public class EntidadesContext : DbContext
{
    public EntidadesContext (DbContextOptions<EntidadesContext> options)
        : base(options)
    {
    }

    public DbSet<WebApplication1.Models.Entidad> Entidades { get; set; }
}

In your context, you specify to EF the classes you want to work with, that is, the tabals of your BD.

The other step is to declare the contexts in Startup.cs it would look something like this:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();

        services.AddDbContext<TrabajadoresContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("TrabajadoresConnection")));

        services.AddDbContext<EntidadesContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("EntidadesConnection")));
    }

This way you can use several contexts or what is translated to work with several connections in a single App. Suppose I want to call the Entities in a view of the Worker controller.

 public class TrabajadorsController : Controller
{
    private readonly TrabajadoresContext _context;
    private readonly EntidadesContext _entidadesContext;

    public TrabajadorsController(TrabajadoresContext context, EntidadesContext entidadescontext)
    {
        _context = context;
        _entidadesContext = entidadescontext;
    }

public IActionResult Create()
    {
        ViewData["EntidadId"] = new SelectList(_entidadesContext.Entidades, "Id","Nombre");
        return View();
    }

}

In this Controller I have defined 2 contexts _context that refers to the context itself TrabajadorContext and _entidadesContext to work with the DB of Entities. Let's assume that in the Worker class we have EntityId as a parameter. We add a select in the create view to be able to select the Entity.

<div class="form-group">
            <label asp-for="EntidadId" class="control-label"></label>
            <select asp-for="EntidadId" asp-items="ViewBag.EntidadId" class="form-control"></select>
            <span asp-validation-for="EntidadId" class="text-danger"></span>
        </div>

This way in the select all the Entities are shown which are in another BD. I hope it helps you

    
answered by 10.11.2017 в 16:59