Skip to content

Instantly share code, notes, and snippets.

@pwelter34
Last active November 28, 2022 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwelter34/827f6a33957a31f18f4eb92d8141e23d to your computer and use it in GitHub Desktop.
Save pwelter34/827f6a33957a31f18f4eb92d8141e23d to your computer and use it in GitHub Desktop.
ConcurrencyToken
public readonly struct ConcurrencyToken : IEquatable<ConcurrencyToken>
{
public static readonly ConcurrencyToken None = new(Array.Empty<byte>());
public byte[] Value { get; }
public ConcurrencyToken(byte[] value)
{
Value = value ?? Array.Empty<byte>();
}
public ConcurrencyToken(string value)
{
Value = string.IsNullOrEmpty(value) ? Array.Empty<byte>() : Convert.FromHexString(value);
}
public override string ToString()
{
return Value != null ? Convert.ToHexString(Value) : null;
}
public override bool Equals(object obj)
{
return obj is ConcurrencyToken token && Equals(token);
}
public bool Equals(ConcurrencyToken other)
{
return EqualityComparer<byte[]>.Default.Equals(Value, other.Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public static implicit operator byte[](ConcurrencyToken token) => token.Value;
public static implicit operator string(ConcurrencyToken token) => token.ToString();
public static implicit operator ConcurrencyToken(byte[] token) => new(token);
public static implicit operator ConcurrencyToken(string token) => new(token);
}
public class ConcurrencyTokenTypeHandler : SqlMapper.TypeHandler<ConcurrencyToken>
{
public override ConcurrencyToken Parse(object value)
{
if (value is string textToken)
return new ConcurrencyToken(textToken);
if (value is byte[] byteToken)
return new ConcurrencyToken(byteToken);
return ConcurrencyToken.None;
}
public override void SetValue(IDbDataParameter parameter, ConcurrencyToken value)
{
parameter.Value = value.Value;
parameter.DbType = DbType.Binary;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment