Cannot switch a connection string in LLBL Gen Pro - sql-server-2008

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

Related

"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

Using SSIS 2012 package parameters for connection properties

I am trying to write ETL that collects data from many identical server into a central repository. What I'm trying to do is write one package with source address, user id and password as parameters and execute the package once per server to be copied.
Is this doable? How can I use parameters to create a source?
I meant to ask how to parametrize the connection manager (is that even a real word?), not where to store the connection parameters. The answer is simple:
Create package parameters for Server, Database, User ID and Password
Create a connection manager as part of defining a data flow component
once a connection is defined, right-click on the connection manager at the bottom of the package design screen and select "Parametrize".
Select "ServerName" in the property drop-down
Select "Use existing parameter" or create new parameter if skipped step 1
If using existing parameter, select it from the drop down
Click OK to save (gotta do it after each parameter)
Repeat steps 4-7 for the rest of the parameters
You can store parameters in a table. Query the table with a sql task and store the results in a object variable. You can then use this variable in a for loop. Use expressions in SSIS to change values of your connection during each loop iteration.
Several books outline this method. Here is a code example.
Here are some steps - hopefully I didn't miss anything. You mention a server "Address", but I'm not sure exactly what you are trying to do. This example queries multiple sql servers.
You create the variables, SQL_RS with type of object, SRV_Conn with type of string. This holds my servername. In the execute SQL task, I have a query which returns the names of sql servers I want to query. Then set the following properties:
SELECT RTRIM(Server) AS servername
FROM ServerList_SSIS
WHERE (Server IS NOT NULL)
and coalesce(exclude,'0') <> 'True'
and IsOracle is Null
Execute SQL Task > General > ResultSet = "Full Result Set"
Execute SQL Task > Result Set Tab "Result Set Name = 0", Variable Name = "User::SQL_RS"
So we have a list of server names in the SQL_RS variable now.
ForEach > Collection > Enumerator = "Foreach ADO Enumerator"
ForEach > Collection > Enumerator Configuration > ADO Object source Variable = User::SQL_RS
This maps the first column of the SQL_RS object to the SRV_Conn variable, so each iteration of the loop will result in a new value in this variable.
ForEach > Variable Mappings > Variable = User::SRV_Conn, Index = 0
Inside the ForEach are some other sql execs, performing queries on sql databases, so I need to change the ServerName of my 'MultiServer' connection. I have another connection for the initial query that got me the list of servers to query. Making the connection dynamic is done in properties of the connection - right-click the connection > properties. Click the ellipses to the right of the expressions.
Connection > Properties > Expressions > Property = ServerName, Expression = "#[User::SRV_Conn]"
Note: The index value of 0 for the variable mapping works for Native OLEDB\SQL Server Native Client. If you're using another db provider, you may need to use other index types - this makes setup more confusing.
OLEDB = 0,1
ADO.NET = #Varname
ADO = #Param1, Param2
ODBC = 1,2
Full listing here.

Why Doesn't The EntityConnection Object Contain the Login Password?

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.

How can I get the database name from a Perl MySQL DBI handle?

I've connected to a MySQL database using Perl DBI. I would like to find out which database I'm connected to.
I don't think I can use:
$dbh->{Name}
because I call USE new_database and $dbh->{Name} only reports the database that I initially connected to.
Is there any trick or do I need to keep track of the database name?
Try just executing the query
select DATABASE();
From what I could find, the DBH has access to the DSN that you initially connected with, but not after you made the change. (There's probably a better way to switch databases.)
$dbh->{Name} returns the db name from your db handle.
If you connected to another db after connected with your dbh, using mysql query "USE db_name", and you did not setup a new perl DBI db handle, of course, $dbh->{Name} will return the first you previously connected to... It's not spontaneic generation.
So to get the connected db name once the db handle is set up - for DBI mysql:
sub get_dbname {
my ($dbh) = #_;
my $connected_db = $dbh->{name};
$connected_db =~ s/^dbname=([^;].*);host.*$/$1/;
return $connected_db;
}
You can ask mysql:
($dbname) = (each %{$dbh->selectrow_hashref("show tables")}) =~ /^Tables_in_(.*)/;
Update: obviously select DATABASE() is a better way to do it :)
When you create a connection object it is for a certain database. In DBI's case anyway. I I don't believe doing the SQL USE database_name will affect your connection instance at all. Maybe there is a select_db (My DBI is rusty) function for the connection object or you'll have to create a new connection to the new database for the connection instance to properly report it.
FWIW - probably not much - DBD::Informix keeps track of the current database, which can change if you do operations such as CREATE DATABASE. The $dbh->{Name} attribute is specified by the DBI spec as the name used when the handle is established. Consequently, there is an Informix-specific attribute $dbh->{ix_DatabaseName} that provides the actual current database name. See: perldoc DBD::Informix.
You could consider requesting the maintainer(s) of DBD::MySQL add a similar attribute.