Why Doesn't The EntityConnection Object Contain the Login Password? - sql-server-2008

I've got an app that uses EF CTP5.
In this particular situation, i need to degrade to some classic ADO.NET (in order to read multiple result sets in a stored procedure, which EF does not support).
As such, im trying to use the existing connection string from the EntityConnection object, like this:
var ctx = (this as IObjectContextAdapter).ObjectContext;
var efCon = ((EntityConnection) (ctx.Connection)).StoreConnection;
var con = new SqlConnection(efCon.ConnectionString);
con.Open(); // exception thrown
When i debug, i see that the ConnectionString does not contain the password, only the data source, username, database, etc.
Is this a security thing why they've removed it? Does EF hide the password somewhere and only use it when it executes stored procedures itself?
The EF connection string is not like classic ADO.NET connection strings, as it has metadata info.
So it looks like im going to have to strip out the part of the connection string that i need, put that in the web.config and pass it through to the Repository.
Surely there must be a better way!

Try adding "Persist Security Info=True;" to the context connection string. This worked for me.

Related

Calling MySQL Stored Procedure from .NET DB Context throws "Only MySqlParameter objects may be stored'"

I am using .NET Core 5 DBContext to access MYSQL Stored procedure to get results with the below code :
var param = new SqlParameter("#word", word);
var result = _context.History.FromSqlRaw("EXEC GETHISTORY #word", param).ToList();
if (result != null)
{
retval = (IEnumerable<HistoryDM>)result;
}
Yet it throws the below exception,
MySql.Data.MySqlClient.MySqlException: 'Only MySqlParameter objects may be stored'
So, what is the error trying to tell me and how can I fix it ?
SqlParameter is for SqlClient, i.e. SQL Server. You want a new MySqlParameter (the connection, command, parameter and reader types are all provider-specific). Or better: ask the connection to create the parameter, or use a tool that will deal with the ADO.NET internals for you.
OK, looks like when one knows it it is relatively simple :
Object result = _context.History.FromSqlInterpolated($"CALL ADDHISTORY ({word})").ToList();
So, both CALL is used (instead of EXEC) and parentheses around the parameter, which is also like the MySQL native call. No black magic here.
Thanks a lot for your support #Marc !!

"Must declare the scalar variable #Idx" when using a Dapper query on SQL server via OleDb

This code works when the connection is made to an accdb database:
Dim customer = connection.Query(Of Klantgegevens)("Select Actief,Onderhoudscontract From Klantgegevens Where Klantnummer=#Idx", New With {.Idx = customerId}).SingleOrDefault
But the code below gives the error about the Idx parameter when the connection is made to a SQL server database that has a table with the same structure:
Dim customer = connection.Query(Of Klantgegevens)("Select Actief,Onderhoudscontract From [dbo.Klantgegevens] Where Klantnummer=#Idx", New With {.Idx = customerId}).SingleOrDefault
What is going wrong here? I had hoped that by using Dapper I would be able to write database agnostic code. But it seems that is not the case!
If you are using an ODBC/OLEDB connection, then my first suggestion would be: move to SqlClient (SqlConnection). Everything should work fine with SqlConnection.
If you can't do that for some reason - i.e. you're stuck with a provider that doesn't have good support for named parameters - then you might need to tell dapper to use pseudo-positional parameters. Instead of #Idx, use ?Idx?. Dapper interprets this as an instruction to replace ?Idx? with the positional placeholder (simply: ?), using the value from the member Idx.
This is also a good fix for talking to accdb, which has very atypical parameter usage for an ADO.NET provider: it allows named parameter tokens, but all the tokens all replaced with ?, and given values from the positions of the added parameters (not via their names).

EntityFramework on MySql changing connection string does not change results data

I'm working with EntityFramework 5.0 and MySql. I have generated model from database, and my application now have to connect on multiple database with same structred data.
So i have to dynamic change connection string based on some info.
I try to change database name even from config section of connection string, and with EntityConnectionStringBuilder, but i had the same result: my new connection is stored correctly, but data returned are of the first database.
From WebConfig:
add name="dbIncassiEntities" connectionString="metadata=res:///DAL.Modelincassi.csdl|res:///DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl;provider=Devart.Data.MySql;provider connection string="user id=root ... database=dbname2"" providerName="System.Data.EntityClient" />
From code:
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = "user id=...database=dbname2";
entityBuilder.Metadata = #"res://*/DAL.Modelincassi.csdl|res://*/DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl";
var context = new dbIncassiEntities(entityBuilder.ToString());
My constructor:
public dbIncassiEntities(string conn)
: base(conn)
{
}
What am i missing?
UPDATE
I can see that calling a query directly from SqlQuery, results returned are correct,
while using the generated entities i retrieve wrong data.
var test = context.Database.SqlQuery<string>(
"SELECT cognomenome FROM addetto limit 0,1").ToList();
But calling..
var oAddetto = from c in context.addettoes select c;
So my problem is only on the model itsself, and manually changing the generated schema
<EntitySet Name="addetto" EntityType="dbIncassiModel.Store.addetto" store:Type="Tables" Schema="dbname2" />
..i'll get the right information.
My question now is: how can i change in code these informations??
Any help is really appreciated!!
Thanks, David
Ok, i've found a workaround for now.
I simply clear the shema name on the designer, and now i can call the generated entities succesfully. Hope this can help anyone else.
David
While I could not remove the Schema in the designer, I removed it directly in the .edmx file. Do a full text search for Schema="YourSchema" in an XML editor of your choice and remove the entries. After that, changing the connection string is enough.
Downside is, the Visual Studio designer and mapping explorer won't work properly anymore.
This seems to be more of a dotConnect issue rather than MySQL, since the problem also exists for the Oracle adapter:
http://forums.devart.com/viewtopic.php?t=17427

Cannot switch a connection string in LLBL Gen Pro

I have two databases with the same schema inside a Sql 2008 R2 Server, of which names are Database1 and Database2. I connected and performed queries on the Database1, and then changed to Database2 to fetch my entities using the following code
this.ConnectionString = "Server=TestServer; Database=Database2;Trusted_Connection=true";
using (IDataAccessAdapter adapter = new DataAccessAdapter(this.ConnectionString))
{
var entities = new EntityCollection<T>();
adapter.FetchEntityCollection(entities, null);
return entities;
}
(The connection string was set before executing the code).
I debugged the application and looked at the value of the connection string, it pointed to the Database2.
However, when I executed the above code, the result was return from the Database1. And if I looked at SQL Profiler, the statement was executed against Database1.
So, could anyone know what was going on? Why the query was executed against the Database1, not Database2.
PS: If I used the above connection string with plain ADO.NET, I was able to retrieve data from Database2.
Thanks in advance.
I have figured out what was going on. The reason was: by default LLBL Gen Pro uses fully qualified names like [database1].[dbo].[Customer] to access database objects, and the catalog is specified when generating entities. So you can't access objects just by changing the connection string.
Hence, to change to another database you have to override the default catalogue by using following code
var adapter= new DataAccessAdapter(ConnectionString, false,
CatalogNameUsage.ForceName, DbName)
{CommandTimeOut = TenMinutesTimeOut};
More information can be found at the following link

with linq to sql, where is the database connection information stored?

With linq to sql, where is the database connection information stored?
How could I override the database to another database on a per query basis?
You can't do it per-query; but you can per-data-context. Just pass in a different connection or connection-string to the constructor:
string connectionStringA = ..., connectionStringB = ...
using(var ctxA = new FooContext(connectionStringA)) {...}
...
using(var ctxB = new FooContext(connectionStringB)) {...}
using(SqlConnection conn = ...)
using(var ctxC = new FooContext(conn)) {...}
The database connection for linq is in the web.config or application.config files.
You pass it to the DataContext instance.
With a generated DataContext subclass, the default constructor will use project .Settings, and thus from the .config file.
As aleemb said, the database information is stored in the config files. Check the one in the project where you created your dbml map.
That said - the DatabaseContext has a constructor that takes the connection string as a parameter. However, I'm not sure there's a good way to override that on a per query basis without creating a new DatabaseContext object. Which really could cause you issues in the future if you're creating entities from two different DatabaseContext objects.