我如何从数据库中存储和获取正确的Guid? [英] How I can store and get correct Guid from database?

查看:77
本文介绍了我如何从数据库中存储和获取正确的Guid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我正在使用MySql数据库开发ASP.Net,C#Web应用程序...

for DAL(数据访问层)我正在使用Entity Framework和Linq ...

我有一个带有ProcessId(数据类型 - 二进制(16))的数据库表来存储Guid ..
$ b将数据插入数据库表时,$ b

...它正在使用ProcessId ='9e5ba38f-cfb0-4dcb-8365-c4536acb7272'(由Guid.newGuid()生成;)

并且在从表中获取相同记录时它给了我一些差异。 ProcessId

为什么会这样?如何从数据库中存储和获取正确的Guid?



寻找紧急回复....请

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

推荐答案

如果由于某种原因转换为二进制文件失败,您可以尝试使用sql server类型uniqueidentifier。也许你比较幸运。



因为我们谈论MySQL,所以这可能不是一个选项。

而不是.NET部分你应该确保相应的转换GUID。



对于通过Guid.NewGuid()生成的.NET Guid类型值,您可以将它们传递给MySqlCommand参数if你将guid值转换成字节数组。

这可以通过Guid.ToByteArray()完成,如下所述:



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:

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));
        }
    }
}


这篇关于我如何从数据库中存储和获取正确的Guid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆