Set database name dynamically in LINQ to SQL - linq-to-sql

I am using LINQ to SQL to connect to database from my application. When I am changing environment from production to staging, I can update my connection string in web.config.
But there is one more value I need to update when environment changes. That is database name. In LINQ to SQL designer file, database name is mentioned as attribute like-
[System.Data.Linq.Mapping.DatabaseAttribute(Name="somedbname")]
How can I pick up value of Name dynamically from some config file?
Any help is really appreciated.

as mentioned on the
http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.databaseattribute.name.aspx
"The DatabaseName is used only if the connection itself does not specify the database name."
so you can delete this attribute and all is gonna work fine!

I've used a wrapper class to provide a context along the lines of
public DataContext Context = new DataContext(SqlConnectionString); //much simplified

I fixed this problem by editing the .dbml file outside of Visual Studio (the designer doesn't seem to allow access to the DatabaseAttribute) and getting rid of the name property here:
<Database Name="BadName" Class="OutputDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
(note that the accepted answer is no longer correct: this attribute was overriding my connection string)

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).

Schema name in Create index statement while generating datanucleus JDO schema

I am trying to generate schema from the DataNucleus SchemaTool for a mysql database, that will store countries and states. Here is a sample of that code:
#PersistenceCapable
Public class State{
private String shortCode;
private String fullName;
#Column(allowsNull = "true",name="country_id")
private Country countryId;
}
The following are my schemaGeneration properties:
datanucleus.ConnectionDriverName=com.mysql.jdbc.Driver
datanucleus.ConnectionURL=jdbc:mysql://localhost:3306/geog
datanucleus.ConnectionUserName=geog
datanucleus.ConnectionPassword=geogPass
datanucleus.schema.validateTables=true
datanucleus.mapping.Catalog=geog
datanucleus.mapping.Schema=geog
In my Country class as well, I have a mapping from a Collection, so that the FK reference for States to the Country table is built correctly.
But there is one problem. In the SQL script generated, the Index part has the Schema name as part of the index name itself, which fails the entire script. Here is that piece:
CREATE INDEX `GEOG`.`MST_STATE_N49` ON `GEOG`.`MST_STATE` (`COUNTRY_ID`);
Notice the schema name in the GEOG.MST_STATE_N49 part of the index' name.
I tried setting the schema and catalog name to blank but that yields a ''.MST_STATE_N49 which still fails.
I am using MySQL Server 5.7.17 using the 5.1.42 version of the JDBC driver (yes, not the latest) on Data nucleus JDO 3.1
Any hints on how I can get rid of the schema/catalog name in the generated DDL?
Why are you putting "datanucleus.mapping.Schema" when using MySQL ? MySQL doesnt use schema last I looked. Similarly the "datanucleus.mapping.Catalog" is effectively defined by your URL! MySQL only actually supports JDBC catalog, mapping on to "database", as per this post. Since DataNucleus simply uses the JDBC driver then catalog is the only useful input.
Consequently removal of both schema and catalog properties will DEFAULT to the right place.
After the comment above from Neil Stockton, I commented out both the properties and it worked. Effectively, this is what is needed:
datanucleus.ConnectionDriverName=com.mysql.jdbc.Driver
datanucleus.ConnectionURL=jdbc:mysql://localhost:3306/geog
datanucleus.ConnectionUserName=geog
datanucleus.ConnectionPassword=geogPass
datanucleus.schema.validateTables=true
Hopefully, I can get the answer to the other question (Pt. 2 in my reply-comment above) as well.

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

XmlReaderParsingException: The start element with name <...> and namespace "http..." was unexpected

This is for BizTalk 2010. I am running into a very strange issue that I've not been able to find a solution either using my favorite search engine's results or elsewhere.
I added several SQL Server 2008 table schemas to BizTalk. Set up orchestration and mapping without any problems. BizTalk was able to use WCF_Custom SQL Adapter using XML/BTSAction to insert data to the SQL tables identified in the XML.
Some of those tables had data inserted just fine, except two. Both had the same error. The error was pulling from a third table's namespace. Here's the error in full -- notice that the namespace, ns, is for ns46:professionalAddendum as is expected, but somehow, somewhere, BizTalk is pulling a different namespace, ns35, from a different table:
Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The start element with name "ClaimFilingIndicatorCode" and namespace "http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalCOBAdjustmentsAncillary" was unexpected. Please ensure that your input XML conforms to the schema for the operation.
<ns2:Insert xmlns:ns2="http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalAddendum">
<ns2:Rows>
<ns46:professionalAddendum xmlns:ns46="http://schemas.microsoft.com/Sql/2008/05/Types/Tables/dbo">
<ns46:uid_claim>1b8f20e9-0517-4f00-9ee2-99d5f04d1573</ns46:uid_claim>
ERROR>>>>> <ns35:ClaimFilingIndicatorCode xmlns:ns35="http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalCOBAdjustmentsAncillary">17</ns35:ClaimFilingIndicatorCode>
<ns46:ClaimFrequencyTypeCode>1</ns46:ClaimFrequencyTypeCode>
<ns46:ProviderAcceptAssignmentCode>B</ns46:ProviderAcceptAssignmentCode>
<ns46:BenefitsAssignmentCertificationIndicator>Y</ns46:BenefitsAssignmentCertificationIndicator>
<ns46:ReleaseofCode>Y</ns46:ReleaseofCode>
<ns46:ProviderOrSupplierSignatureIndicator>N</ns46:ProviderOrSupplierSignatureIndicator>
</ns46:professionalAddendum>
</ns2:Rows>
</ns2:Insert>
Is there a way to fix this? Really weird.
Thanks all!
It's tough to know exactly what is going on without seeing your full schema, but I have seen it where the case of a table name changes somewhere, and then the corresponding namespace no longer matches.
For example:
http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalAddendum
vs
http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/ProfessionalAddendum
I'm posting up what I found. The map and orchestration are both fine for the most part. There was a Scripting functoid in the mapper that used an inline XSLT to map from the source schema to the destination schema, and the offending namespace was in that XSLT code. When I changed the schema's tables, their corresponding namespace #s changed as well thus causing this problem to manifest itself. Having said that, I fixed it up to be flexible should the schema tables' namespace #s change again.
Problem solved. Now I got to fix up a few of those. :)
Thanks all for your help.

Could not find server 'dbo' in sys.servers

I have a lot of services which query the database. All of them work fine but one service calling a stored procedure gives me following error:
Could not find server 'dbo' in
sys.servers. Verify that the correct
server name was specified. If
necessary, execute the stored
procedure sp_addlinkedserver to add
the server to sys.servers.
I have not idea why all the other stored procedures work fine and this one not...
By the way, I use SubSonic as data access layer.
Please run select name from sys.servers from the server which you mentioned as default server in configuration file.
Here in name column values should match with your server names used in the report query.
e.g serverXXX.databasename.schema.tablename
serverXXX should be there in the result of select name from sys.servers otherwise it gives error as got.
It sounds like there is an extra "." (or two) in the mapping - i.e. it is trying to find server.database.schema.object. Check your mapping for stray dots / dubious entries.
Also make sure that the server name matches what you think it is. If you rename the host that SQL Server is running on, you need to rename the SQL Server, too.
http://www.techrepublic.com/blog/datacenter/changing-the-name-of-your-sql-server/192
I had another issue with the same exception so I'll post here if someone stumble upon it:
Be careful if you specify the server name in synonyms. I had a different server name on my staging machine and production and it caused the same 'cannot find server'-error.
(Guess you shouldn't use synonyms that much anyway but it's useful in some migration scenarios)
In my case i was facing same issue with following ,
SqlCommand command = new SqlCommand("uspx_GetTemplate", connection);
but after adding square bracket to stored procedure name it get solved.
SqlCommand command = new SqlCommand("[uspx_GetTemplate]", connection);