Reputation: 1073
How can Entity Framework detect if it is created from SQL Server or Oracle by code? Is there any property or method which returns the source database type?
Upvotes: 4
Views: 1593
Reputation: 4160
Entity Framework knows it from connection being used in DbContext
(either from connection string, because it has Provider
part or from instance itself directly). You can get the "type" from DbContext.Database.Connection
. I.e.:
DbContext.Database.Connection.GetType().Name
Upvotes: 6
Reputation: 7824
I can't think of a better way of doing this than getting the DbProviderFactory and checking its type.
If you create a class library solution and install the NUnit and EntityFramework nuget packages you can run the below.
using System.Data.Common;
using System.Data.Entity;
using System.Diagnostics;
using NUnit.Framework;
namespace efProviderChooser
{
public class MyThing
{
public int Id { get; set; }
}
public class MyContext : DbContext
{
public DbSet<MyThing> Things { get; set; }
}
public class Test
{
[Test]
public void CanGetProvider()
{
var context = new MyContext();
var dbProviderFactory = DbProviderFactories
.GetFactory(
context.Database.Connection);
Debug.WriteLine(dbProviderFactory.GetType());
//gives one of
//System.Data.EntityClient.EntityProviderFactory
//System.Data.Odbc.OdbcFactory
//System.Data.OleDb.OleDbFactory
//System.Data.OracleClient.OracleClientFactory
//System.Data.SqlClient.SqlClientFactory
//this list could change!
// here I get SqlClient
Assert.That(dbProviderFactory.GetType().ToString().Contains("SqlClient"));
}
}
}
Upvotes: 2