Cannot use Turkish characters with Entity Framework - c#

We have a large SaaS ASP .NET 4.0 application used internationally. We are slowly migrating our classic ADO dataproviders toward Entity Framework.
We use MS Sql server 2008. For Turkish customers we use a Turkish collation "Turkish_CI_AS" for character columns. I.e. 8 bit varchar fields (we don't use 16bit nvarchar columns)
Now I encountered a problem when I add new objects with EF. Special characters like 'ş' are changed:
using (TestEntities myEntity = new TestEntities())
{
MyObject test = new MyObject()
{
TestString = "baş"
};
myEntity.MyObjects.AddObject(test);
myEntity.SaveChanges();
}
When I step through with the debugger, "test.TestString" is still "baş" in this line of code:
myEntity.MyObjects.AddObject(test);
However in the database the field "TestString" has the value "bas". The 'ş' is saved as a 's' This does not happen with my old dataprovider methods.
How can I add Turkish characters to my database with EF? Anyone has some good suggestions? I tried quite some things but can't figure it out :)
tnx, Frank
edit
running the profiler on a little test setup shows this:
exec sp_executesql N'insert [dbo].[TestObjects]([TestChar])
values (#0)
select [TestId]
from [dbo].[TestObjects]
where ##ROWCOUNT > 0 and [TestId] = scope_identity()',N'#0 varchar(255)',#0='Bas'
apparently sql receives the wrong value, it's really .NET who's responsible.

Ok I figured it out. In MySql it is possible to add encoding info in the connection string, Microsoft sql doesn't allow this.
EF seems to determine the encoding by looking at the default database collation. In our setup the database collation was Latin1, while the tables with customer specific data have collation "Turkish_CI_AS".
So I have two options:
1) change the default collation for the whole database (impact on
system and config tables etc)
2) change my columns to nvarchar
Changing to unicode will be done in the end, for now we'll use some good old ADO.NET which just works! :)
tnx for thinking with me

Related

C# PostgreSQL date format exception

I have format exception when i trying to add '9/30/2019 5:15:54 PM'(DD-MM-YYYY) to my database.
I'm already SET datestyle = 'ISO, DMY'. So now i can use it like:
INSERT INTO products(name, createdat) values ('test', '9/30/2019 5:15:54 PM')
I have the same SQL command in C# and PostgreSQL, but it works only in Postgre-pgAdmin(nice joke C#).
How can fix this error in C#?
Well if you insert a valid Postgres timestamp literal, it should work everywhere:
INSERT INTO products (name, createdat)
VALUES
('test', '2019-09-30 17:15:54'::timestamp);
Perhaps the setting you configured were only valid from the session originating from pgAdmin, but not with the Postgres driver which C# is using. In any case, the default Postgres timestamp literal is ISO compliant (your version is not), which is always a good thing.

Loading data from MySQL database to C# DGV

I have MySQL database on QNAP and I created local copy using UwAmp. In MySQL Workbench it looks fine, but when I want to load data into my own DGV, it's not fine at all. Every cell have the same value and it's number 1. Also as I see there is some problem with encoding.
Problem on screen
Here's my connection string:
Server=IP;Database=database;Uid=user;Pwd=password;convert zero datetime=True; default command timeout=500000; Connection Timeout = 500000
I've encountered a similar problem, and it's almost always been the primary key not being set correctly in existing databases or the key not being set where you define the schema. Might be worth checking into.
Hope this helps!
I found source of problem. MySQL Workbench (I have 6.3 and I don't know how it look in other versions) doesn't export views properly. It doesn't generate script like:
select o.id, o.number, c.name from order o join client c on o.client_id = c.client_id order by o.id
But something like this:
select '1' as id, '1' as number, '1' as name;
I have no idea why, but manual export fixed the issue.

MySql C# Insert Error. Incorrect string value: '\xE1ra'

I'm using the C# .NET Mysql Connector, and when running this query:
INSERT INTO convos (`userid`,`time`,`from`,`content`,`read`,`deleted`, `ip`, `source`, `charname`, `to`) VALUES ('3', '1347396787', 'Chára', '........', '0', '0', '0.0.0.0:0000', 'C', 'óóóíííí', 'óóóíííí');
I get the following error:
Incorrect string value: '\xE1ra' for column 'from' at row 1
I understand my encoding, everything was configured for utf8, utf8_general_ci. Database, table and columns are configured for utf8. The data is sent from the client in utf8.
If i use a 3rd party tool like, Workbench to insert the query or use the mysql command line it works fine. I don't know if there is a bug with the connector or i need to be doing something else with the values before insert?
Any idea?
Thanks
Is there any in mysql to covert to the correct type?
I believe you need to alter the column's char set:
use below code for those columns which is using UTF-8.
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
Unicode string prefix with N
First see your table convos and make sure columns data types is either one of nchar, nvarchar and You must precede all Unicode strings with a prefix N when you deal with Unicode string constants in SQL Server
Tyr:
insertQuery = "INSERT INTO convos (`userid`,`time`,`from`,`content`,`read`,`deleted`, `ip`, `source`, `charname`, `to`) VALUES
(N'3', N'1347396787', N'Chára', N'........', N'0', N'0', N'0.0.0.0:0000', N'C', N'óóóíííí', N'óóóíííí')";
I figured this out, its taken a while but it seems i was setting the charset too often. The database, tables, columns are all in UTF8. When i made a connection i had "CHARSET=UTF8" in the connection string. I was also running "SET NAMES 'utf8' COLLATE 'utf8_general_ci'" everytime i made a connection. I dropped the CHARSET=UTF8 and "SET NAMES 'utf8' COLLATE 'utf8_general_ci'" and its all working now.
Update it
INSERT INTO convos (`userid`,`time`,`from`,`content`,`read`,`deleted`, `ip`, `source`, `charname`, `to`) VALUES ('3', '1347396787', 'Chara', '........', '0', '0', '0.0.0.0:0000', 'C', 'óóóíííí', 'óóóíííí');
I think for "chara"in your 3rd value gives it
For someone who has tried all the suggestions, and nothing has worked (like myself), it is worth checking what MySQL types are your fields mapped to in C#. My text fields were automatically mapped as MySqlDbType.Blob and that was causing the error. I changed the type to MySqlDbType.Text, and I don't see the error any more.
Here is my original response to a similar thread:
https://stackoverflow.com/a/16989466/2199026
config mysql like below. it will solve the unicode error when insert into mysql from java or C#
enter image description here

Using MSSQL CE in C# getting error, and can't figure our why,

I have a problem with inserting into a MSSQL CE database,
locCon.Open();
SqlCeCommand locCmd = locCon.CreateCommand();
locCmd.CommandText = "INSERT INTO user (ID,FName,LName,Email) VALUES('"+this.id+"','"+this.fName+"', '"+this.lName+"','"+this.email+"')";
locCmd.ExecuteNonQuery();
When running this I get
There was an error parsing the query. [Token line number = 1, Token line offset = 13, Token in error = user]
Now i cant see anything wrong with the query although this is the firsr time ive used MS SQL of examples ive seen the syntax for mysql and msssql are identical well for inserts anyway. Is there soemthing obviously wrong with this?
Thanks
I think "user" is a reserved word in the database. Try replacing this:
INSERT INTO user (ID,FName,LName,Email) VALUES (
with this:
INSERT INTO [user] (ID,FName,LName,Email) VALUES (
(I think it' square brackets for MSSQL CE, since it is for other MSSQL engines.)
The square brackets basically tell the query engine, "This is an identifier for an object in the database." They're commonly used to wrap the names of database objects which contain spaces, since those otherwise wouldn't parse correctly. But it's also useful for objects which are reserved words.
You may have to put brackets around the user part like so:
INSERT INTO [user]
this is because user can be a reserved word. putting [] around reserved words in SQL allows them to be used as field and table names.
One other major point is that you are constructing your query from some text inputs. This exposes you to SQL injection attacks. To avoid this I would highly recommend that you use Sql Parameters instead which help to prevent this. See this link:
http://msdn.microsoft.com/en-us/library/ff648339.aspx

What do these .NET auto-generated table adapter commands do? e.g. UPDATE/INSERT followed by a SELECT

I'm working with a legacy application which I'm trying to change so that it can work with SQL CE, whilst it was originally written against SQL Server.
The problem I am getting now is that when I try to do dataAdapter.Update, SQL CE complains that it is not expecting the SELECT keyword in the command text. I believe this is because SQL CE does not support batch SELECT statements.
The auto-generated table adapter command looks like this...
this._adapter.InsertCommand.CommandText = #"INSERT INTO [Table] ([Field1], [Field2]) VALUES (#Value1, #Value2);
SELECT Field1, Field2 FROM Table WHERE (Field1 = #Value1)";
What is it doing? It looks like it is inserting new records from the datatable into the database, and then reading that record back from the database into the datatable? What's the point of that?
Can I just go through the code and remove all these SELECT statements? Or is there an easier way to solve my problem of wanting to use these data adapters with SQL CE?
I cannot regenerate these table adapters, as the people who knew how to have long since left.
It is just updating the object with the latest values from the database, after an update. Always seemed a little unecessary to me but hey...
These are a nuisance from a maintenance point of view - if you have the option, you'll save yourself a lot of hassle by abstracting this all out to a proper data layer.
allows that the field values might be altered by trigger(s) on the table. Sensible enough, I'd have thought, in auto-generated boilerplate.
though the select statement is a tad whacky to assume that field1 is the primary key... but maybe the autogen code makes sure it is before generating this bit of code.

Categories

Resources