DotNetInfo
DotNetInfo

Reputation: 3404

Accessing Connection property using DbContext

I am upgrading my practice Entity Framework code to v4.1. In old version, I had my context class deriving from ObjectContext but with new release of EF 4.1, they have provided a good DbContext API.

I am basically trying to convert the code so that it works from Database First approach to Code First approach. Playing around with EF 4.1

In old code, I had something like

context.Connection.BeginTransaction(isolationLevel);

where the context Type was deriving from ObjectContext.

In v4.1 I haven't got access to Connection property from context. How can I do that?

Upvotes: 26

Views: 32669

Answers (4)

nathanchere
nathanchere

Reputation: 8098

In the brave new .Net Core world, you can use:

using Microsoft.EntityFrameworkCore;

context.Database.GetDbConnection();

Upvotes: 11

hazimdikenli
hazimdikenli

Reputation: 6019

It is in the DbContext and it should be public.

dbContext.Database.Connection.ConnectionString

also:

dbContext.Database.Connection.BeginTransaction(isolationLevel)

Upvotes: 55

Chandermani
Chandermani

Reputation: 42669

The new DBContext has

context.Database.Connection.BeginTransaction() 

method with some overloads. Do a Goto Definition in Visual Studio to see the methods.

Upvotes: 4

DotNetInfo
DotNetInfo

Reputation: 3404

You can use something like

((IObjectContextAdapter)context).ObjectContext.Connection.BeginTransaction(isolationLevel);

Upvotes: 2

Related Questions