Convert byte[] or object to GUID

前端 未结 5 1831
别那么骄傲
别那么骄傲 2021-02-12 10:20

I assigned some value to object data type like,

object objData =dc.GetDirectoryEntry().Properties[\"objectGUID\"].Value;

this object retun the

5条回答
  •  别那么骄傲
    2021-02-12 10:58

    Though the manual casting suggested above works, there's a way to do this automatically.

    1. You can use the official SQLite provider instead of the one from Microsoft. Use its SQLiteConnectionStringBuilder to configure a Connection that understands your Guids as Guids:
    var builder = new SQLiteConnectionStringBuilder("Data Source=./mydatabase.db") { BinaryGUID = true };
    var connStr = builder.ToString();
    return new SQLiteConnection(connStr);
    

    Here's the official SQLite provider: https://www.nuget.org/packages/System.Data.SQLite.Core/

    1. If using Dapper, you can have it automatically convert byte arrays to Guid using this class, which should be registered once as soon as your app starts:
    public class GuidTypeHandler : SqlMapper.TypeHandler
    {
        public override Guid Parse(object value)
        {
            var valueAsBytes = (byte[])value;
            return new Guid(valueAsBytes);
        }
    
        public override void SetValue(System.Data.IDbDataParameter parameter, Guid value)
        {
            var guidAsBytes = value.ToByteArray();
            parameter.Value = guidAsBytes;
        }
    }
    
    // And the registration in Startup.cs or equivalent:
    SqlMapper.AddTypeHandler(new GuidTypeHandler());
    

    Source: Dapper Issue #718 - GitHub

提交回复
热议问题