基于Entityframework代码的配置

时间:2016-11-08 10:05:52

标签: entity-framework sqlite

我试图摆脱App.config及其EntityFramework(v6)设置,并将其移至代码中(不想使用连接字符串和密码部署配置)。

开放时会抛出以下异常:System.Data.Entity.Core.EntityException: The underlying provider failed on Open.

我使用带有加密和数据库第一实体模型的sqlite3 db。

[DbConfigurationType(typeof(DatabaseConfiguration))]
public partial class TestEntities : DbContext
{
    public TestEntities () :
        base((DatabaseConfiguration.GetConnectionString("TestEntities", @"\\\\ABT\01_Tools\Test\DB\test.db", "someDummyPw")))
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Employee> Employees { get; set; }
}

public class SQLiteConnectionFactory:IDbConnectionFactory
{
    public DbConnection CreateConnection(string nameOrConnectionString)
    {
        return new SQLiteConnection(nameOrConnectionString);
    }
}

public class DatabaseConfiguration:DbConfiguration
{
    public DatabaseConfiguration()
    {
        SetDefaultConnectionFactory(new SQLiteConnectionFactory());
        SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
        SetProviderFactory("System.Data.SqlClient", SqlClientFactory.Instance);
        SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
        //SetProviderFactory("System.Data.EntityClient", EntityProviderFactory.Instance);

        SetProviderServices("System.Data.SQLite.EF6", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
    }

    public static string GetConnectionString(string efModelName, string databaseFilePath, string password)
    {
        // Initialize the connection string builder for the underlying provider.
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
        {
            DataSource = databaseFilePath,
            Password = password
        };

        // Initialize the EntityConnectionStringBuilder.
        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
        entityBuilder.Provider = "System.Data.SQLite.EF6";

        // Set the provider-specific connection string.
        entityBuilder.ProviderConnectionString = sqlBuilder.ToString();

        // Set the Metadata location.
        entityBuilder.Metadata = string.Format(@"res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", efModelName);

        return entityBuilder.ConnectionString;
    }
}

任何想法?

0 个答案:

没有答案