简体   繁体   English

检测实体框架(Oracle或SQL Server)中的dbms类型

[英]Detect dbms type in Entity Framework (Oracle or SQL Server)

How can Entity Framework detect if it is created from SQL Server or Oracle by code? 实体框架如何通过代码检测它是从SQL Server还是Oracle创建的? Is there any property or method which returns the source database type? 是否有任何属性或方法返回源数据库类型?

Entity Framework knows it from connection being used in DbContext (either from connection string, because it has Provider part or from instance itself directly). 实体框架从DbContext中使用的连接中DbContext (来自连接字符串,因为它具有Provider部分或直接来自实例本身)。 You can get the "type" from DbContext.Database.Connection . 您可以从DbContext.Database.Connection获取“类型”。 Ie: 即:

DbContext.Database.Connection.GetType().Name

I can't think of a better way of doing this than getting the DbProviderFactory and checking its type. 我想不出比获取DbProviderFactory并检查其类型更好的方法。

If you create a class library solution and install the NUnit and EntityFramework nuget packages you can run the below. 如果您创建一个类库解决方案并安装NUnit和EntityFramework nuget包,则可以运行以下命令。

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"));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM