Mike Mike - 1 year ago 71
C# Question

How to use EF Code-First without an app.conf file?

If I use an app.conf file to define the connection for a SQL CE 4.0 DB, my app works fine.

How can I "initialize the connection" (hope this is the right term...) without an app.conf, in the code?

Here is what I have so far (not much):

SqlCeConnectionStringBuilder builder = new SqlCeConnectionStringBuilder();
builder["Data Source"] = "db.sdf";

//What is missing here?

PartyDB DB = new PartyDB();

var dinners = from d in DB.Dinners
select d;

Any hint is highly appreciated.

Answer Source

J. Tihon's answer helped me. I am adding the following for future reference. I initialized the Database.DefaultConnectionFactory in the constructor.

public partial class MyDb: DbContext
    public static string Connection

            var result = new SqlCeConnectionStringBuilder();

            result["Data Source"] = "MyDatabaseFile.sdf";

            return result.ToString();

    public MyDb()
        : base(Connection)
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

    protected override void OnModelCreating(DbModelBuilder modelBuilder)


    public DbSet<MyTable> MyTable { get; set; }