Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
Hi All,

I am working on ASP.Net,C# web application with MySql Database...
for DAL(Data Access Layer) I am using Entity Framework and Linq...
I am having a db table with Column ProcessId(DataType - binary(16)) to store Guid..

while inserting data into database table ...it's taking ProcessId = '9e5ba38f-cfb0-4dcb-8365-c4536acb7272' (which is generated by Guid.newGuid();)
and while fetching same record from table it's giving me some diff. ProcessId
why is it so? How I can store and get correct Guid from database?

Looking out for urgent reply....Please
Posted
Comments
Kornfeld Eliyahu Peter 7-Jul-15 10:07am    
It seems to me that you are storing a string representation of the GUID into the database and not a binary value...
Tty to send it as byte array - https://msdn.microsoft.com/en-us/library/system.guid.tobytearray(v=vs.110).aspx

1 solution

If conversion to binary fails for some reason you could try to use the sql server type uniqueidentifier. Maybe you're more lucky then.

Since we speak about MySQL this might not be an option afterall.
Instead on the .NET part you should make sure the GUID is converted accordingly.

For .NET Guid-type values generated via Guid.NewGuid() you can pass them to a MySqlCommand Parameter if you cast the guid value as Byte Array.
This can be done via Guid.ToByteArray() as mentioned below:

C#
string connectionString = string.Format("Server={0};Database={1};Uid={2};pwd={3}", "server", "database", "user", "password");

Guid orgId = Guid.NewGuid();
Guid fromDb = Guid.Empty;

using (MySqlConnection conn = new MySqlConnection(connectionString))
{
    conn.Open();

    //How to insert .NET GUID into MySQL
    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO test (id) VALUES (?id)", conn))
    {
        cmd.Parameters.Add("id", MySqlDbType.Binary).Value = orgId.ToByteArray();
        cmd.ExecuteNonQuery();
    }

    //How to retrieve GUID-Value from MySQL
    using (MySqlCommand cmd = new MySqlCommand("SELECT id FROM test", conn))
    {
        using (MySqlDataReader r = cmd.ExecuteReader())
        {
            r.Read();
            fromDb = new Guid((byte[])r.GetValue(0));
        }
    }
}
 
Share this answer
 
v2
Comments
johannesnestler 9-Jul-15 8:15am    
yes, I thought the same, why not define it as uniqueidentifier in the first place, after reading the question again I saw MySql-Database....
cybie04 9-Jul-15 8:24am    
Oh. Didn't realize this in the first place. Anyway I updated Solution according to MySQL (see above)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900