Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF with SQL server application role

I need to use application rule security on sql server. And i want to use Enity Framework Code First.

After a successful login my connection is set to application role. I then create my DbContext using this connection.

But: EF expects a closed connection object. And closing a connection drops the application role.

How can i solve this dilemma?

like image 564
okrumnow Avatar asked Feb 03 '26 15:02

okrumnow


1 Answers

I managed to get this work with two steps:

Switch connection pooling off, which is mentioned all the time for connections using application roles. As i have a desktop application, this is no problem for me.

Add a handler to DbConnection.StateChanged and activate the application role on every opening of the connection. Without connection pooling, it is not necessary to sp_unsetapprole on closing. So this works for me:

context.Database.Connection.StateChanged += (sender, args) =>
  if (args.CurrentState == ConnectionState.Open) {
    activateAppRole((DbConnection)sender, ...);
  }
}

I guess, if Pooling is vital for someone, she may call sp_unsetapprole on closing the connection in this same handler.

like image 63
okrumnow Avatar answered Feb 05 '26 03:02

okrumnow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!