Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get database information with entityframework database first?

When I use Entity Framework codefirst I can use the following code to get my database connection string:

var db = new dbContext();
Console.Writeline(db.Database.Connection.ConnectionString);

But when I do database first, Database is not available. How do I (from code at runtime) go about getting the database connection string that is being used by entity framework?

like image 480
JonnyBoats Avatar asked Apr 07 '11 18:04

JonnyBoats


People also ask

How do I use database first approach in Entity Framework?

Step 1 − Let's create a new console project with DatabaseFirstDemo name. Step 2 − To create the model, first right-click on your console project in solution explorer and select Add → New Items… Step 3 − Select ADO.NET Entity Data Model from middle pane and enter name DatabaseFirstModel in the Name field.

How does Entity Framework get data from database?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database. LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries. It uses your derived context and entity classes to reference database objects.

How do I retrieve data from EDMX?

In the Model Browser, right-click the . edmx file and select Update Model from Database. Expand the Tables, Views, and Stored Procedures nodes, and check the objects you want to add to the . edmx file.


2 Answers

The code:

var db = new dbContext();
Console.Writeline(db.Database.Connection.ConnectionString);

works always. So If you created entity model from your database and used DbContext Generator T4 template you can still use it.

If you instead used ObjectContext API you must call this:

var connection = context.Connection as EntityConnection;
if (connection == null) throw new ...;
var storeConnectionString = connection.StoreConnection.ConnectionString;
like image 126
Ladislav Mrnka Avatar answered Oct 13 '22 06:10

Ladislav Mrnka


... And the specific connection string properties can then be exposed:

using System.Data.SqlClient;



    internal static string GetDatabaseName()
    {
        using (var _db = new MyProjectEntities())
        {
            return new SqlConnectionStringBuilder(_db.Database.Connection.ConnectionString).InitialCatalog;
        }
    }
like image 45
Justin Avatar answered Oct 13 '22 08:10

Justin