Can I use a DBContext connection to run a SQL statement before the first EF object is loaded?

.net entity-framework

Question

I'm really new to EF and have looked around for a solution without success.

In essence, I need to run a stored procedure to set up some internal security when I establish a connection to the database in EF. This would then restrict the data that is brought back in the EF interactions.

I've done some research and discovered information that suggests the following should function:

String currentUser = "Name";
_db = new DBContext();
if (_db.Database.Connection.State != ConnectionState.Open) {
    _db.Database.Connection.Open();
}

DbConnection conn = _db.Database.Connection;
DbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "storedproc";

DbParameter user = cmd.CreateParameter();
user.DbType = DbType.String;
user.Direction = ParameterDirection.Input;
user.Value = currentUser.ToUpper();
cmd.Parameters.Add(user);
cmd.ExecuteNonQuery();

var customer = (from c in _db.Customer where c.ACCOUNT == inputAccount select c);           
response = customer.First<Customer>();

However, when I attempt this, the LINQ query returns the error "EntityConnection can only be built with a closed DBConnection."

Anybody have any idea whether this is even conceivable?

For my database access, which connects to a 10.2.0.3.0 server, I'm using EF4.1 and the Oracle ODP.NET Beta.

Any assistance is much appreciated.

[EDIT]

Using what Craig said and the following steps, I was able to solve this:

  • supplying a DbContext connection
  • I connected before starting to work.

By forcing EF to maintain the connection, I was able to run my security stored procedure and ensure that my security configuration was still effective.

the following coding:

OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString);
_db = new DBContext(conn);
_db.UnderlyingContext().Connection.Open();
_db.UnderlyingContext().ExecuteStoreCommand("execute storedproc");
_db.SaveChanges();
var customer = (from c in _db.Customer where c.ACCOUNT == inputAccount select c);
response = customer.First<Customer>(); 
1
3
9/22/2011 3:42:09 PM

Accepted Answer

Avoid breaking through to the link in that manner. Apply zzz-5 zzz.

9
9/22/2011 1:09:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow