我可以使用Entity Framework的连接,还是应该创建一个新的? [英] Can I use the connection from Entity Framework or should I create a new one?
问题描述
我有一个SQLite数据库,可以使用 System.Data.SQLite 访问。数据库被读入我的Entity Framework Objectcontext。但是,在某些情况下,我还需要直接访问数据库。
I have a SQLite Database that I access using System.Data.SQLite. The database is read into my Entity Framework Objectcontext. However, I also need direct access to the database in certain cases.
- 是否应该使用与Entity Framework对象相同的连接上下文正在使用?也就是说
ObjectContext.Connection
? - 如果是,我如何访问?将
Entities.Connection 转换为
SQLiteConnection
会导致无法投射类型为System.Data.EntityClient的对象.EntityConnection'to type'System.Data.SQLite.SQLiteConnection'。 - 如果没有,我应该创建一个单独的连接,打开它,
- Can I / Should I use the same connection that my Entity Framework object context is using? I.e.
ObjectContext.Connection
? - If yes, how can I access it? Casting
Entities.Connection
toSQLiteConnection
results in "Unable to cast object of type 'System.Data.EntityClient.EntityConnection' to type 'System.Data.SQLite.SQLiteConnection'." - If not, should I create a seperate connection, open it and keep it open for the application duration, or should I open and close the connection every time I want to access the database with it?
推荐答案
ObjectContext.Connection
是一个 EntityConnection
。您可以通过以下方式获取商店连接:
ObjectContext.Connection
is an EntityConnection
. You can get the store connection via:
var sc = ((EntityConnection)ObjectContext.Connection).StoreConnection;
您可以将其转换为 SQLiteConnection
。
如果需要,可以使用此连接。
It's OK to use this connection if you need it.
但是,如@Chris所说,你可以使用 ObjectContext.ExecuteStoreQuery
等,如果这样做为你。
But, as @Chris mentioned, you can just use ObjectContext.ExecuteStoreQuery
, etc., if that will do for you.
这篇关于我可以使用Entity Framework的连接,还是应该创建一个新的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!