How to use dynamic connection string for SQL Server CE?

自古美人都是妖i 提交于 2019-12-08 20:18:29

问题


I used SQL Server CE 4.0 in my windows app and use Entity Framework to create a model of it.

It works fine but my problems is that it doesn't have a constructor to change the connection string, and by default it reads the connection string from the app.config file.

 using (var Context = new MyEntitiesModel(//has no constructor))
 {
        ...
 }

I create a dynamic connection string and

  using (var Context = new MyEntitiesModel())
   {
         Context.Database.Connection.ConnectionString = entityConnection.ConnectionString;
   }

It works fine by this way but if I remove another connection string in app.config file it gave me this.

error = invalid metasource ....

because the default constructor uses it

How can I handle it?


回答1:


Create your own constructor. MyEntitiesModel is partial class you can add your own partial part of the class and add constructor accepting a connection string.

public partial class MyEntitiesModel {
    public MyEntitiesModel(string connectionString) : base(connectionString) { }
}



回答2:


Im using DbContext. There are several Overload Constructors eg: ObjectContext also has a similar set of constructor overloads.

System.Data.Entity DbContext example

Context = new BosMasterEntities(nameOrConnectionString: nameOrConnectionString);

You can connect to multiple Dbs at same time.



来源:https://stackoverflow.com/questions/12660683/how-to-use-dynamic-connection-string-for-sql-server-ce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!