Search code examples
c#entity-frameworkfirebird-embedded

Firebird embeded and EntityFramework code first: what's the correct way to set connection string and provider?


I have to use Firebird embeded database and Entity Framework. I have downloaded the Connector and if i use this code:

using FirebirdSql.Data.FirebirdClient;

[...]

string exePath = Path.GetDirectoryName(
    new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

FbConnectionStringBuilder fbStringBuilder = new FbConnectionStringBuilder();
fbStringBuilder.ServerType = FbServerType.Embedded;
fbStringBuilder.UserID = "SYSDBA";
fbStringBuilder.Password = "MASTERKEY";
fbStringBuilder.Dialect = 3;
fbStringBuilder.Charset = "UTF8";
fbStringBuilder.ClientLibrary = Path.Combine(exePath, "fbembed.dll");
fbStringBuilder.Database = Path.Combine(exePath, "test.fdb");


if (!File.Exists(Path.Combine(exePath, "test.fdb")))
{
    FbConnection.CreateDatabase(fbStringBuilder.ToString());
}

FbConnection fbConn = new FbConnection(fbStringBuilder.ToString());

try
{
    fbConn.Open();

    Console.WriteLine("OK");
}
catch (Exception ex)
{
    Console.WriteLine("ERROR");
    Console.WriteLine(ex.Message);
    Console.ReadKey();
}
finally
{
    fbConn.Close();
}

Everything works. But when I try to use that connection string with DbContext:

public class FirebirdEmbededExampleDbContext : DbContext
{
    public FirebirdEmbededExampleDbContext(string connString) : base(connString)
    {
        this.Database.Connection.ConnectionString = connString;
    }

    public DbSet<ItemA> ItemsA { get; set; }
    public DbSet<ItemB> ItemsB { get; set; }
}

it fails with message:

Unsupported keyword: 'server type'

It looks like EF isn't using Firebird provider. How should I use it ?


Solution

  • Your DbContext should look like this:

    public class FirebirdEmbededExampleDbContext : DbContext
    {
        public FirebirdEmbededExampleDbContext(string connString) 
          : base(new FbConnection(connString), true)
        { }
    
        public DbSet<ItemA> ItemsA { get; set; }
        public DbSet<ItemB> ItemsB { get; set; }
    }
    

    You have to give it a clue it should be using FirebirdClient.