1

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.

  1. Can I / Should I use the same connection that my Entity Framework object context is using? I.e. ObjectContext.Connection?
  2. If yes, how can I access it? Casting Entities.Connection to SQLiteConnection results in "Unable to cast object of type 'System.Data.EntityClient.EntityConnection' to type 'System.Data.SQLite.SQLiteConnection'."
  3. 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?

3 Answers 3

1

ObjectContext.Connection is an EntityConnection. You can get the store connection via:

var sc = ((EntityConnection)ObjectContext.Connection).StoreConnection;

You can cast that to the SQLiteConnection.

It's OK to use this connection if you need it.

But, as @Chris mentioned, you can just use ObjectContext.ExecuteStoreQuery, etc., if that will do for you.

Sign up to request clarification or add additional context in comments.

2 Comments

I ended up using ObjectContext.ExecuteStoreQuery which worked perfectly. Thanks
LOL I just ended up reading this question and using the answer, without realising it was me who originally posted it! Craig, if I could mark it twice, I would!
0

If you're using the DBContext API you can actually execute a direct query by using this: aDBContext.Database.SqlQuery

I wouldn't be surprised if something similar exists for the ObjectContext API, but I barely used that one and thus can't tell you what it is.

Now if for some reason you can't (or don't want) to do that, I'd create a new connection for your custom queries. Put them in a Using and close it as soon as you're done with it.

Comments

0

Entity Framework has built in methods for executing raw SQL queries if that's what you need to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.