开发者

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

开发者 https://www.devze.com 2023-03-18 20:20 出处:网络
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?

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 =开发者_如何学C 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.


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
    {
        get
        {

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

}


There are various method of instantiating a DbContext (which your PartyDb probably derives from). I recommend you take a look at this blog-post. For you specific problem, this paragraph from the blog-post should fit:

You can pass a full connection string to DbContext instead of just the database or connection string name. By default this connection string is used with the System.Data.SqlClient provider; this can be changed by setting a different implementation of IConnectionFactory onto context.Database.DefaultConnectionFactory.


If you have oracle provider and all the answers didn"t help try this: Changing the app.config entry in entityFramework**defaultConnectionFactory** to

type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework" ......

Now all you need to send to the constructore is a regular connection string:

public partial class MyModel : DbContext { public MyModel(String ConnectionString) : base(ConnectionString) { } ..........

0

精彩评论

暂无评论...
验证码 换一张
取 消